码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Contains Duplicate & Contains Duplicate II

时间:2015-05-29 15:23:30      阅读:105      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!