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 i and 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

217. Contains Duplicate 的拓展, 那道题只需判断数组中是否有重复值,而这题限制了数组中只许有一组重复的数字,而且坐标差最多k。

解法: 哈希表Hash table

Java:

class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer, Integer> index = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (i - index.getOrDefault(nums[i], -k - 1) <= k) return true;
index.put(nums[i], i);
}
return false;
}
} 

Python:

class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {boolean}
def containsNearbyDuplicate(self, nums, k):
lookup = {}
for i, num in enumerate(nums):
if num not in lookup:
lookup[num] = i
else:
# It the value occurs before, check the difference.
if i - lookup[num] <= k:
return True
# Update the index of the value.
lookup[num] = i
return False  

C++:

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;
else m[nums[i]] = i;
}
return false;
}
};

  

类似题目:

[LeetCode] 217. Contains Duplicate 包含重复元素

[LeetCode] 220. Contains Duplicate III 包含重复元素 III

   

All LeetCode Questions List 题目汇总

最新文章

  1. win 8 换 win7 注意事项
  2. 文件上传——servlet实现
  3. HDU1495 非常可乐
  4. Python 的格式化字符串format函数
  5. Android(java)学习笔记234: 服务(service)之音乐播放器
  6. sql大小转换函数
  7. java微信平台,发源码
  8. SQL truncate 、delete与drop区别
  9. P1137 旅行计划-----洛谷
  10. Mac OSX下Sublime Text配置使用Ctags实现代码跳转
  11. 浅谈python的对象的三大特性之继承
  12. 使用FileUpload实现Servlet的文件上传
  13. kubernetes in action - Replication Controller
  14. Runtime详解(下)
  15. Android路径之Javascript基础-笔记
  16. html总结2
  17. JAVA获取不同操作系统的分隔符等参数
  18. 尚硅谷面试第一季-10SpringMVC的工作流程
  19. v-charts使用心得
  20. FAX modem和传真协议简介

热门文章

  1. 面向切面编程AOP——加锁、cache、logging、trace、同步等这些较通用的操作,如果都写一个类,则每个用到这些功能的类使用多继承非常难看,AOP就是解决这个问题的,python AOP就是装饰器
  2. appium+python自动化64-使用Uiautomator2执行driver.keyevent()方法报错解决
  3. @CrossOrigin:解决跨域问题
  4. oracle取随机数,取固定行数的数
  5. 如何使用 淘宝 NPM 镜像
  6. 使用SpringBoot访问jsp页面
  7. RedisTemplate在项目中的应用
  8. LeetCode 1079. Letter Tile Possibilities
  9. 001_Visual Studio 显示数组波形
  10. C# 监控网速