【217】存在重复元素
给你一个整数数组 nums
。如果任一值在数组中出现 至少两次 ,返回 true
;如果数组中每个元素互不相同,返回 false
。
示例 1:
输入:nums = [1,2,3,1] 输出:true
示例 2:
输入:nums = [1,2,3,4] 输出:false
示例 3:
输入:nums = [1,1,1,3,3,4,3,2,4,2] 输出:true
提示:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
自己做:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int len = nums.size();
unordered_map<int, int> num_map;
for(int i = 0; i < len; i++){
if(num_map.find(nums[i]) != num_map.end()){
num_map[nums[i]] += 1;
}else{
num_map[nums[i]] = 1;
}
}
for (unordered_map<int, int>::const_iterator it = num_map.cbegin(); it != num_map.cend(); ++it) {
if(it->second >= 2){
return true;
}
}
return false;
}
};
// 哈希表:key为值,value为该值的次数
time:11:38
复杂度分析:
时间复杂度:O(N)
空间复杂度:O(N)
官方题解:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> s;
for(int x:nums){
if(s.find(x) != s.end()){
return true;
}else{
s.insert(x);
}
}
return false;
}
};
【389】找不同
给定两个字符串 s
和 t
,它们只包含小写字母。
字符串 t
由字符串 s
随机重排,然后在随机位置添加一个字母。
请找出在 t
中被添加的字母。
示例 1:
输入:s = "abcd", t = "abcde" 输出:"e" 解释:'e' 是那个被添加的字母。
示例 2:
输入:s = "", t = "y" 输出:"y"
提示:
0 <= s.length <= 1000
t.length == s.length + 1
s
和t
只包含小写字母
class Solution {
public:
char findTheDifference(string s, string t) {
string ss = s + t;
int len = ss.size();
unordered_map<char, int> add_map;
for(int i = 0; i < len; i++){
if(add_map.find(ss[i]) != add_map.end()){
add_map[ss[i]] += 1;
}else{
add_map[ss[i]] = 1;
}
}
for(auto it = add_map.begin(); it != add_map.end(); ++it) {
if(it->second % 2 != 0){
return it->first;
}
}
return ' ';
}
};