Easy
553678FavoriteShare
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 absolute difference between iand j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
C++:
/*
* @Author: SourDumplings
* @Date: 2019-08-21 21:10:14
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/contains-duplicate-ii/
*/
class Solution
{
public:
bool containsNearbyDuplicate(vector<int> &nums, int k)
{
map<int, int> mI; // 记录每一个数的上一个数的位置
int n = nums.size();
const int MAXD = k + 1;
for (int i = 0; i < n; i++)
{
int num = nums[i];
if (mI.find(num) != mI.end())
{
if (i - mI[num] <= k)
{
return true;
}
}
mI[num] = i;
}
return false;
}
};
Java:
import java.util.Hashtable;
import java.util.Map;
/*
* @Author: SourDumplings
* @Date: 2019-08-21 21:31:08
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/contains-duplicate-ii/
*/
class Solution
{
public boolean containsNearbyDuplicate(int[] nums, int k)
{
Map<Integer, Integer> map = new Hashtable<>();
int n = nums.length;
for (int i = 0; i < n; i++)
{
int num = nums[i];
if (map.containsKey(num) && i - map.get(num) <= k)
{
return true;
}
map.put(num, i);
}
return false;
}
}