《leetCode》:Contains Duplicate II

来源:互联网 发布:apt get yum rpm 编辑:程序博客网 时间:2024/06/06 00:07

题目

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j]  and the difference between i and j is at most k.

思路一:时间复杂度为O(n*k)

此题比较简单,利用两层for循环即可解决,值得注意的是限制条件是:j-i<=k;并不是j-i<=k+1;

bool containsNearbyDuplicate(int* nums, int numsSize, int k) {    if(nums==NULL||numsSize<2){        return false;    }        for(int i=0;i<numsSize-1;i++){        int temp=nums[i];        int count=0;        for(int j=i+1;j<numsSize;j++){            count++;            if(temp==nums[j]&&count<=k){//注意:至多为k,即j-i<=k;不是i和j两端都不算进去                return true;            }            if(count>=k){                break;            }        }    }    return false;}

思路二:利用Set容器,时间复杂度为O(n)

实现代码如下:

public boolean containsNearbyDuplicate(int[] nums, int k) {        if(nums==null||k<1){            return false;        }        HashSet<Integer> hs=new HashSet<Integer>();        for(int i=0;i<nums.length;i++){            if(hs.add(nums[i])==false){//当此元素重复的时候,就不能放入Set容器中                return true;            }            if(hs.size()==k+1){                hs.remove(nums[i-k]);//就是删除此时hs中的第一个元素。            }        }        return false;    }
0 0