训练营打卡Day06

训练营打卡Day06

题15:242. 有效的字母异位词

思路

  • 哈希表的统计问题,很简单
class Solution {
public:
    bool isAnagram(string s, string t) {
        vector<int>dic(26, 0);
        for(const char& ch: s)
            dic[ch-'a']++;
        for(const char& ch: t)
            dic[ch-'a']--;
        for(const int& num: dic)
        {
            if(num) return false;
        }
        return true;
    }
};

题16:349. 两个数组的交集

思路

  • set的筛选问题
  • 先用一个set1去重nums1
  • 再用一个set2,去重nums2与set1
  • set2的存放元素就是结果
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int>s1, s2;
        for(auto num1: nums1)
            s1.insert(num1);
        for(auto num2: nums2)
        {
            if(s1.count(num2))
                s2.insert(num2);
        }

        vector<int>ans;

        for(auto num: s2)
            ans.push_back(num);
        
        return ans;
        
    }
};

题17:202. 快乐数

思路

  • 将每一次快乐数的结果存入set中
  • 如果快乐数不在set出现过,意味着将会进入死循环,return false
  • 快乐数为1时,return true;
class Solution {
public:
    int get(int n)
    {
        int result = 0;
        while(n)
        {
            result += (n%10) * (n%10);
            n /= 10;
        }
        return result;
    }

    bool isHappy(int n) {
        set<int>s;
        n = get(n);
        while(n)
        {
            if(n == 1) return true;
            if(s.count(n)) return false;
            s.insert(n);
            n = get(n);
        }
        return false;
    }
};

题18:1. 两数之和

思路

  • 遍历元素,用map来存储“值”和“下标”
  • 遍历的时候再去寻找之前target-当前值的“值”
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int>m;
        for(int i = 0; i < nums.size(); i++)
        {
            if(m.count(target-nums[i]))
                return{ i, m[target-nums[i]]};
            else
                m[nums[i]] = i;
        }
        return {};
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值