leetcode刷题 242, 349, 202, 1

当我们需要查询一个元素是否出现过,或者一个元素是否在集合里的时候,就要第一时间想到哈希法。

242.有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1: 输入: s = "anagram", t = "nagaram" 输出: true

示例 2: 输入: s = "rat", t = "car" 输出: false

说明: 你可以假设字符串只包含小写字母

class Solution {
public:
    bool isAnagram(string s, string t) {
        vector<int> cnt(26, 0);//记录每种字母出现的次数
        for(int i = 0; i < s.size(); ++i){//一个串加次数,一个串减次数
            cnt[s[i] - 'a']++;
        }
        for(int j = 0; j < t.size(); ++j){
            cnt[t[j]-'a']--;
        }
        for(int k = 0; k < 26; ++k)
            if(cnt[k] != 0)
                return false;
        return true;
    }
};

349. 两个数组的交集

题意:给定两个数组,编写一个函数来计算它们的交集。

class Solution {//leetcode上的题目数字的范围是0~1000,故使用1001大的数组进行统计。若无范围则使用unordered_set统计
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<bool> visit(1001, false);
        vector<int> nums;
        for(int i = 0; i < nums1.size(); ++i)
            visit[nums1[i]] = true;
        for(int j = 0; j < nums2.size(); ++j)
            if(visit[nums2[j]] == true){
                nums.push_back(nums2[j]);
                visit[nums2[j]] = false;
            }
                
        return nums;
    }
};

第202题. 快乐数

编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。

如果 n 是快乐数就返回 True ;不是,则返回 False 。

无限循环但始终变不到1这个条件我们使用再次出现之前计算得到的结果则为false。此时也是用unorder_set收集曾经出现过的值。
class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> nums;//收集数据的set
        if(n < 1)
            return false;
        int sum = 0;
        int a;
        while(1){
            while(n != 0){
                a = n%10;//得到数中的每一位
                n = n/10;
                sum += pow(a, 2);
            }
            if(sum == 1)//为快乐数
                return true;
            else{
                if(nums.find(sum) != nums.end())//循环回来又出现不为1的数,判定为false
                    return false;
                else{
                    nums.insert(sum);//加入数字
                    n = sum;
                    sum = 0;
                }
                    
            }
        }
    }
};

1. 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

如果现在的数和曾经出现过的数之和为target,则成功找到。由于需要返回相应元素的下标,使用unorder_map记录数据。
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> map;//定义存储数据的map
        for(int i = 0; i < nums.size(); ++i){
            auto iter = map.find(target - nums[i]);
            if(iter != map.end())//成功找到
                return {iter->second, i};
            else//未成功找到,加入map,为后续寻找做基础
                map.insert(pair<int, int>{nums[i], i});
        }
        return {};
    }
};
posted @ 2024-12-29 22:05  arbiter9  阅读(5)  评论(0)    收藏  举报