问题描述(217):
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.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
源码(217):
第一想法就是用一个map存着所有的元素,然后每次找一下他是否存在,如果存在则直接返回true。时间O(n),空间因为用了hash损失会大一点。
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, bool> help;
int n = nums.size();
for(int i=0; i<n; i++){
if(help.find(nums[i]) != help.end()) return true;
else help[nums[i]] = true;
}
return false;
}
};
问题描述(218):
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j]and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
源码(218):
和上一题一样,用一个map存着出现过的元素以及其对应的位置。如果出现了重复的数字,判断其位置之间的差距是否小于等于k,若是直接返回true,否则更新map。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> st;
int n = nums.size();
for (int i=0; i<n; i++){
if(st.count(nums[i])){
if(i - st[nums[i]] <= k) return true;
else st[nums[i]] = i;
}
else st[nums[i]] = i;
}
return false;
}
};