[LeetCode] Contains Duplicate & Contains Duplicate II

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表的应用。

原文地址:https://www.cnblogs.com/easonliu/p/4538283.html