leetcode_219题——Contains Duplicate II(哈希表)
2015-07-05 16:48
489 查看
Contains Duplicate II
Total Accepted: 13284 Total Submissions: 51898My SubmissionsQuestion Solution
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 iand j is at most k.
Hide Tags
Array Hash Table
Have you met this question in a real interview?
Yes
No
Discuss
这道题我采用的是map哈希表来做的,在这道题中,采用哈希表来记录已近遍历过的数,
题目需要求的是在这个数组中是否存在两个相同的数,他们之间的距离小于k
#include<iostream> #include<vector> #include<set> #include<map> #include<utility> using namespace std; #define TRUE 1 #define FALSE 0 bool containsNearbyDuplicate(vector<int>& nums, int k){ if(nums.empty()||nums.size()==1) return FALSE; int len=nums.size(); map<int,int> ma; ma.insert(map<int,int>::value_type(nums[0],0)); for(int i=1;i<len;i++) { int si=ma.count(nums[i]); if(si==1) { map<int,int>::iterator iter=ma.find(nums[i]); int i1=iter->second; if(i-i1<=k) return TRUE; ma.erase(iter); } ma.insert(map<int,int>::value_type(nums[i],i)); } return FALSE; } int main() { int ary[10]={1,0,1,1}; vector<int> nums(ary,ary+4); cout<<containsNearbyDuplicate(nums,1)<<endl; }
相关文章推荐
- A + B Again 2057 有符号的64进位的运算
- POJ 3250 Bad Hair Day(单调栈)
- leetcode 217:Contains Duplicate
- TIME_WAIT状态
- 【原创】CancellableWait
- leetcode 219:Contains Duplicate II
- 微软小冰发威,招摇人工智能
- select document library from certain list
- unity, trail renderer gone black on iOS
- rails 中使用association 生成select 下拉框的一些小技巧
- 图灵 数理逻辑 人工智能 图灵机与计算问题 论文
- LeetCode Contains Duplicate (判断重复元素)
- Leetcode#11 Container With Most Water
- 【Leetcode】Factorial Trailing Zeroes
- 人工智能的篱笆
- 单文档的BCG程序,为什么在CMainFrame::OnCreate最后设置工具条的标题,为什么无效?
- 在Maven的Web项目中用Main函数测试Hibernate
- failed to sync branch You might need to open a shell and debug the state of this repo.
- 172_Factorial Trailing Zeroes
- Filter及FilterChain的使用详解