首页 > 其他 > 详细

[LeetCode] Contains Duplicate & Contains Duplicate II

时间:2015-05-29 15:22:05      阅读:224      评论:0      收藏:0      [点我收藏+]

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.

 1 class Solution {
 2 public:
 3     bool containsDuplicate(vector<int>& nums) {
 4         unordered_set<int> st;
 5         for (auto n : nums) {
 6             if (st.find(n) != st.end()) return true;
 7             else st.insert(n);
 8         }
 9         return false;
10     }
11 };

 

Contains Duplicate II

Given an array of integers and an integer k, return true if and only if 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.

 1 class Solution {
 2 public:
 3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 4         int res = false;
 5         unordered_map<int, int> mp;
 6         for (int i = 0; i < nums.size(); ++i) {
 7             if (mp.find(nums[i]) != mp.end()) {
 8                 res = true;
 9                 if (i - mp[nums[i]] > k) return false;
10             } else {
11                 mp[nums[i]] = i;
12             }
13         }
14         return res;
15     }
16 };

 两题都是简单的hash表的应用。

[LeetCode] Contains Duplicate & Contains Duplicate II

原文:http://www.cnblogs.com/easonliu/p/4538283.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!