[leetcode] 219. Contains Duplicate II
2015-07-24 15:28
423 查看
题目:
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
题意:
给定一个数组,找出是否有nums[i] == nums[j],i与j最多相差k。
思路:
这道题需要考虑到两个元素最多是k的位置上的差距。依旧使用hash的方法。该hash表里存的是当前元素前的k个元素,相当于一个滑动窗口,i每往后移动一位,滑动窗口也需要往后移动一位。对于扫描到i, j在的范围是nums[i - k ]到nums[i-1]之间,即此时hash表中的元素是这k个元素。当i往后扫描到下一位即i+1时,此时j的查询范围因该是nums[i - k +1]到nums[i]之间,所以需要将nums[i-k-1]从hash表中去除。
以上。
代码如下:
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
题意:
给定一个数组,找出是否有nums[i] == nums[j],i与j最多相差k。
思路:
这道题需要考虑到两个元素最多是k的位置上的差距。依旧使用hash的方法。该hash表里存的是当前元素前的k个元素,相当于一个滑动窗口,i每往后移动一位,滑动窗口也需要往后移动一位。对于扫描到i, j在的范围是nums[i - k ]到nums[i-1]之间,即此时hash表中的元素是这k个元素。当i往后扫描到下一位即i+1时,此时j的查询范围因该是nums[i - k +1]到nums[i]之间,所以需要将nums[i-k-1]从hash表中去除。
以上。
代码如下:
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_set<int> numSet; for(int i = 0; i < nums.size(); i++) { if(i > k) { numSet.erase(nums[i - k - 1]); } if(numSet.find(nums[i]) != numSet.end()) return true; numSet.insert(nums[i]); } return false; } };
相关文章推荐
- [leetcode] 217.Contains Duplicate
- ORA-29786: SIHA attribute GET failed with error
- uva 10803 Thunder Mountain (floyd)
- hdu 5291 Candy Distribution 2015 Multi-University Training Contest 1
- hdu 5291 Assignment 2015 Multi-University Training Contest 1
- 在VirtualBox中安装Ubuntu14报错:Failed to open a session for the virtual machine,Unable to load R3……
- 如何定义AIDL跨进程间通信
- [LeetCode]Container With Most Water
- 2015 Multi-University Training Contest 2
- 2015 Multi-University Training Contest 2
- Snail—OC学习之选择器SEL
- Snail—OC学习之可变字典NSMutableDictionary
- Naigos PNP图无法加载最新数据
- Snail—OC学习之字典NSDictionary
- DNN报错:The compiler failed with error code 1.
- 2015 Multi-University Training Contest 2
- Naigos PNP图无法加载最新数据
- UVA 11374 Airport Express 机场快线(单源最短路,dijkstra,变形)
- Chain of Responsibility Pattern
- 朴素贝叶斯方法(Naive Bayes Method)