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

LeetCode OJ 之 Contains Duplicate II (包含重复判断- 二)

2015-06-01 16:09 441 查看

题目:

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 iand j is
at most k.

给定整型数组和整数k,查找是否存在两个相等的数它们的下标之差 <= k。

思路:

使用map保存值和位置。

代码:

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
unordered_map<int , int> map;//键是nums[i],值是i
for(int i = 0 ; i < nums.size(); i++)
{
if(map.find(nums[i]) != map.end() && (i - map[nums[i]] <= k))
return true;
map[nums[i]] = i;//如果已经存在nums[i],则会取代之前的值
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: