给定一个整数数组和一个整数 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
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
mp = {}
for i, v in enumerate(nums):
if v in mp and i - mp[v] <= k:
return True
mp[v] = i
return False
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> mp = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
if (mp.containsKey(nums[i]) && i - mp.get(nums[i]) <= k) {
return true;
}
mp.put(nums[i], i);
}
return false;
}
}
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> mp;
for (int i = 0; i < nums.size(); ++i)
{
if (mp.count(nums[i]) && i - mp[nums[i]] <= k) return true;
mp[nums[i]] = i;
}
return false;
}
};
func containsNearbyDuplicate(nums []int, k int) bool {
mp := make(map[int]int)
for i, v := range nums {
if j, ok := mp[v]; ok {
if i-j <= k {
return true
}
}
mp[v] = i
}
return false
}
public class Solution {
public bool ContainsNearbyDuplicate(int[] nums, int k) {
var mp = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; ++i)
{
if (mp.ContainsKey(nums[i]) && i - mp[nums[i]] <= k)
{
return true;
}
mp[nums[i]] = i;
}
return false;
}
}