Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
47 lines (45 sloc) 1 KB
/*
* @lc app=leetcode.cn id=219 lang=cpp
*
* [219] 存在重复元素 II
*
* https://leetcode-cn.com/problems/contains-duplicate-ii/description/
*
* algorithms
* Easy (32.97%)
* Total Accepted: 11.1K
* Total Submissions: 32.8K
* Testcase Example: '[1,2,3,1]\n3'
*
* 给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j
* 的差的绝对值最大为 k。
*
* 示例 1:
*
* 输入: nums = [1,2,3,1], k = 3
* 输出: true
*
* 示例 2:
*
* 输入: nums = [1,0,1,1], k = 1
* 输出: true
*
* 示例 3:
*
* 输入: nums = [1,2,3,1,2,3], k = 2
* 输出: false
*
*/
//unordered_map
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_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;
m[nums[i]]=i;
}
return false;
}
};
You can’t perform that action at this time.