P4【力扣217,389,496】【数据结构】【哈希表】C++版

【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 ' ';
    }
};

 思路:将两个字符拼接在一块,存入哈希表,只要该哈希表的值是奇数则可认为是被添加的字符

  • 17
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值