LeetCode219:Contains Duplicate II
2015-06-02 17:06
369 查看
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.
直接使用循环时间复杂度为O(N*k),使用stl中的基于红黑树实现的map能减少循环的时间,在O(logN)的时间复杂度内找到元素,或者更进一步使用基于hash表的unordered_map,在常数时间内找到元素。这道题学习到的两个经验:
当想在常数时间内完成查询工作时考虑hash表。
stl中有用hash表实现的数据结构map和set,所以它们也保留了hash表查询上的特点。
代码如下:
直接使用循环时间复杂度为O(N*k),使用stl中的基于红黑树实现的map能减少循环的时间,在O(logN)的时间复杂度内找到元素,或者更进一步使用基于hash表的unordered_map,在常数时间内找到元素。这道题学习到的两个经验:
当想在常数时间内完成查询工作时考虑hash表。
stl中有用hash表实现的数据结构map和set,所以它们也保留了hash表查询上的特点。
代码如下:
class Solution { public: /* 解法一:超时 bool containsNearbyDuplicate(vector<int>& nums, int k) { int length=nums.size(); if(length<=1||k<=0) return false; //将每一个元素与其后面k个元素进行比较 for(int i=0;i<length;i++) { for(int j=1;j<=k&&(i+j)<length;j++) { if(nums[i]==nums[i+j]) return true; } } return false; } */ //解法二,利用stl中的map,记录下整数以及它的下标 bool containsNearbyDuplicate(vector<int>& nums, int k) { //之前直接使用的是map,时间是96ms,后来把map替换成unordered_map时间变成了32ms unordered_map<int ,int> maps; int length=nums.size(); for(int i=0;i<length;i++) { if(maps.count(nums[i]))//如果在maps中找到了该元素,判断它们位置是否小于等于k { if((i-maps[nums[i]])<=k) return true; } maps[nums[i]]=i; } return false; } };
相关文章推荐
- LeetCode_11---Container With Most Water
- setContentView(R.layout.activity_main) Error解决方法
- [ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.3.1:
- email验证
- icvCreateHaarTrainingData和icvCreateBackgroundData
- OpenCms 9.5.1 Container嵌套关系和配置
- AIX 上总有一种压缩方式适合你
- select – Wait for I/O Efficiently
- LeetCode Contains Duplicate II Contains Duplicate III
- xfs文件系统修复方法
- Inheritance and the prototype chain
- tmpFile.renameTo(classFile) failed 错误
- ORA-01078: failure in processing system parameters
- 正确使用Block避免Cycle Retain和Crash
- 无线显示技术:WiDi,WLAN Display,Air Play,Miracast的摘抄
- http://developer.baidu.com/map/jsdemo.htm#a2_1
- 性能测试的问题…
- [leetcode][math] Factorial Trailing Zeroes
- JMeter报错the target server failed to respond--JMeter的坑
- links_container_together