您的位置:首页 > 大数据 > 人工智能

[leetcode] Contains Duplicate II

2015-06-23 13:12 441 查看

Contains Duplicate II

Given an array of integers and an integer k, find out whether there 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.

Have you met this question in a real interview?

方法一:
分析:可以直接定义一个长度最大为k的滑动窗口,用一个set维护窗口内的数字判断是否出现重复,使用两个指针start和end标记滑动窗口的两端,初始都是0,然后end不断进行扩展,扫描元素判断是否出现重复元素,直到发现end-start>k, 就开始移动start,并且在set中移除对应的元素。如果以为扫描到数组末尾还没有发现重复元素,那就可以返回false。时间复杂度和空间复杂度都是 O(N)。

class Solution
{
public:
bool containsNearbyDuplicate(vector<int> &nums, int k)
{
set<int> S;
int start = 0, end  = 0;

for(int i=0; i<nums.size(); i++)
{
if(S.find(nums[i]) != S.end())
return true;
else
{
S.insert(nums[i]);
end++;
}

if(end-start > k)
{
S.erase(nums[start]);
start++;
}
}

return false;
}
};


方法二:
使用map记录出现过的nums[i],并记录对应的位置i,当出现冲突时,比较两者位置关系,如果小于等于k,则返回true,否则记录新位置;如果没有冲突,则说明不含有重复元素。

class Solution
{
public:
bool containsNearbyDuplicate(vector<int> &nums, int k)
{
map<int, int> M;

for(int i=0; i<nums.size(); i++)
{
if(M.find(nums[i]) != M.end() && i-M[nums[i]] <= k)
return true;
else
M[nums[i]] = i;
}

return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: