LeetCode之“散列表”:Contains Duplicate && Contains Duplicate II
2015-06-20 20:39
330 查看
1. Contains Duplicate
题目链接题目要求:
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
代码如下:
class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_map<int, int> hashMap; int sz = nums.size(); for(int i = 0; i < sz; i++) hashMap[nums[i]]++; unordered_map<int, int>::iterator itr = hashMap.begin(); for(; itr != hashMap.end(); itr++) { if(itr->second >= 2) return true; } return false; } };
2. Contains Duplicate II
题目链接题目要求:
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 andj is at most k.
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, int> hashMap; int sz = nums.size(); for(int i = 0; i < sz; i++) { if(hashMap.find(nums[i]) != hashMap.end()) { int j = hashMap[nums[i]]; if(i - j <= k) return true; else hashMap[nums[i]] = i; } else { hashMap[nums[i]] = i; } } return false; } };
相关文章推荐
- leetcode - Container With Most Water
- c++ 返回值为 类的对象 http://blog.csdn.net/zyearn/article/details/9709041
- hdu - 1151 Air Raid(有向无环图的最小路径覆盖)
- http://www.aichengxu.com/view/14872
- assign, retain, copy, weak, strong
- 问题:Bringing up interface eth0: Device eth0 does not seem to be present,delaying initialization. [FAILED]—— 找不到网卡。
- 10 responsibility chain
- 杭电1302 The Snail
- 杭电 ACM HDU Train Problem I
- LeetCode:Container With Most Water 算法题详解
- 1.MyBaits 3.2 简介
- 十大经典数据挖掘算法(9) 朴素贝叶斯分类器 Naive Bayes
- RAID0 RAID1 RAID3 RAID5 RAID6 RAID10 RAID50概念详解
- Exchange发送邮件后卡在草稿箱
- error: server certificate verification failed 解决方案
- Algorithms—42.Trapping Rain Water
- AlphaMobileControls 控件的使用 AlphaImageButton
- 偶尔转帖:AI会议的总结(by南大周志华)
- MonkyTalk学习-6-Verify-WaitFor & WaitForNot
- pthread_cond_wait