博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode----220. Contains Duplicate III
阅读量:4113 次
发布时间:2019-05-25

本文共 2306 字,大约阅读时间需要 7 分钟。

链接:

大意:

给定一个整数数组nums,一个整数k,一个整数n。要求判断数组nums中是否存在不同的两个索引下标i和j,使得 |i - j| <= k 并且 |nums[i] - nums[j]| <= t。例子:

思路:

暂时没想到好方法,只能暴力法先解决了。

代码:

class Solution {    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {        if (k < 0 || t < 0)            return false;        for (int i = 0; i < nums.length; i++) {            for (int j = 1; j <= k && i + j < nums.length; j++) {                // 将int转换为long 为了解决Integer.MAX_VALUE + 1产生的int越界问题                if (Math.abs((long)nums[i] - (long)nums[i + j]) <= t)                    return true;            }        }        return false;    }}

结果:

结论:

效率很低,有待改进。 

改进一:(基于窗口思想)

参考:

public class Solution {    // 窗口思想    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {        if (nums == null || nums.length == 0 || k <= 0) {            return false;        }        final TreeSet
values = new TreeSet<>(); // 存储Long 解决int越界 for (int ind = 0; ind < nums.length; ind++) { final Long floor = values.floor((long)nums[ind] + t); // 得到小于等于nums[ind] + t的最大的数 final Long ceil = values.ceiling((long)nums[ind] - t); // 得到大于等于nums[ind] - t的最小的数 if ((floor != null && floor >= nums[ind]) || (ceil != null && ceil <= nums[ind])) { return true; } values.add((long)nums[ind]); if (ind >= k) { values.remove(new Long(nums[ind - k])); } } return false; }}

改进二:(不使用TreeSet维护有序窗口(TreeSet调整自身顺序也是需要时间,况且使用floor和ceiling函数的时间复杂度为O(log n)),而是使用HashSet维护窗口)

class Solution {    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {        if (nums == null || nums.length == 0) return false;        if (k<1 || t<0) return false;        HashSet
set = new HashSet<>(); for (int i = 0; i < nums.length; i++){ if (t == 0){ if (set.contains(nums[i])) return true; }else{ for (int ii : set){ if (Math.abs((long)((long)ii-(long)nums[i])) <= t) return true; } } set.add(nums[i]); if (set.size() == k+1) set.remove(nums[i-k]); // remove Object } return false; }}

 

 

 

 

转载地址:http://saesi.baihongyu.com/

你可能感兴趣的文章
数字中的1——leetcode233
查看>>
python Leetcode732-我的日程安排表 III
查看>>
python leetcode-502-IPO
查看>>
NLP——IMDB数据集探索
查看>>
准确率、召回率、F1、ROC曲线、AUC曲线、PR曲线基本概念
查看>>
python leetcode-414-第三大的数
查看>>
Python中的collections.Counter模块
查看>>
正向最大匹配法、逆向最大匹配法、双向最大匹配法的分析、语言模型中unigram、bigram、trigram的概念以及N-Gram模型介绍
查看>>
python-leetcode-462-最少移动次数使数组元素相等 II
查看>>
python-leetcode-671-合并二叉树
查看>>
文本挖掘预处理之TF-IDF原理 and 互信息的原理
查看>>
机器学习实战:朴素贝叶斯模型之文本分类
查看>>
细谈 SVM原理
查看>>
一文读懂如何用LSA、PSLA、LDA和lda2vec进行主题建模
查看>>
python-leetcode-390-消除游戏
查看>>
人工神经网络知识、激活函数、正则化、优化技术、Batch Normalization、Layer Normalization
查看>>
python-leetcode-128-最长连续序列
查看>>
从one-hot到word2vec再到FastText
查看>>
python-leetcode-130-被围绕的区域
查看>>
对卷积神经网络、池化层、反卷积以及Text-CNN原理的理解
查看>>