219. Contains Duplicate II 包含重复元素2
来源:互联网 发布:淘宝皮草外套新款 编辑:程序博客网 时间:2024/06/18 17:35
Given an array of integers and an integer k, find out whether there are two distinct indicesi and j in the array such thatnums[i] = nums[j] and the absolute difference betweeni and j is at mostk.
问题解释:是否存在相同的两个元素,他们的距离不超过给定的数值k
class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ if(map.containsKey(nums[i])){ if(i-map.get(nums[i])<=k){ return true; } } map.put(nums[i],i); } return false; }}
采用HashMap(http://blog.sina.com.cn/s/blog_6d2890600100l7id.html),直接查找元素nums[i]是否存在于map中,若不存在则放入,存在则判定是否满足限定条件小于等于k值
class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashSet<Integer> set = new HashSet<>(); for(int i = 0; i < nums.length; i++){ if(set.contains(nums[i])){ return true; } else { set.add(nums[i]); if(i >= k){ set.remove(nums[i - k]); } } } return false; }}利用HashSet也可以解决问题,若set不包含该元素则放入set中,且将第i-k个元素删除,相当于保证set中只有i-1个元素;
这样,只要能在set中找到这个元素,就能判定两个数值之差小于等于k符合限定条件
阅读全文
0 0
- 219. Contains Duplicate II 包含重复元素2
- [Java]Contains Duplicate II 包含重复数字
- Contains Duplicate II 是否包含重复
- 217. Contains Duplicate 包含重复元素
- 【LeetCode-面试算法经典-Java实现】【219-Contains Duplicate II(包含重复元素II)】
- Contains Duplicate 包含重复
- Contains Duplicate 数组中是否包含重复元素
- Contains Duplicate III 是否包含重复元素系列3
- (LeetCode)Contains Duplicate II --- 查找重复的元素升级版
- LeetCode 219 Contains Duplicate II(包含重复数字2)(*)
- Contains Duplicate II-副本包含
- Leetcode:219. Contains Duplicate II(数组是否含有重复元素)
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- 219. Contains Duplicate II
- ansible的playbook模式应用
- yFiles for.net 常见问题
- 【1701H1】【穆晨】【171205】连续第五十六天总结
- 目标检测之三 Win10 +VS2015+双gtx Titan X使用YOLO v2训练VOC数据
- JS实现广度优先搜索得到两点间最短路径
- 219. Contains Duplicate II 包含重复元素2
- 统计数据库中某一天的最高记录
- SpringMVC解决中文字符集乱码问题。
- 后端组作业一(12.12截止)
- Markdown中使用特殊符号(特别是HTML)
- CentOS关机大法之Linux运行级别
- extern关键字
- sizeof与strlen的区别
- rs.insertRow用结果集更新数据库中的表rs.updateString