代码随想录算法训练营day 6 | Leetcode 242 349 202 1

Leetcode 242 有效的字母异位词

哈希表是根据key访问value的数据结构。数组是一种特殊的哈希表。哈希表通过哈希函数将key映射到索引上,如果多于一个元素映射到一个索引上,则发生哈希碰撞,可以使用拉链法(同时存储碰撞元素,再索引)和线性探测法(保证哈希表大小大于数据大小,向下寻找第一个空的位置)。

这道题使用数组实现一个哈希表,将ASCII码映射到0-25:

class Solution {
public:
    bool isAnagram(string s, string t) {
        int record[26] = {0};
        for(int i = 0; i < s.size(); i++){
            record[s[i] - 'a']++;
        }
        for(int i = 0; i< t.size(); i++){
            record[t[i] - 'a']--;
        }
        for(int i = 0; i < 26; i++){
            if(record[i] != 0){
                return false;
            }
        }
        return true;
    }
};

Leetcode 349 两个数组的交集

哈希表有三种使用方法。1. 数组:当元素个数已知有限的时候,可以考虑使用数组实现哈希表;2. set:包括std::set, std::multiset, std::unordered_set,优先使用unordered_set,如果要求集合有序,使用set,如果有重复项,使用multiset;3. map:同样包括std::map, std::multimap, std::unordered_map,set只存储key,map存储key-value对。这道题首先只要求记录数组元素,使用set,其次输出元素无序且无重复项,使用unordered_map。首先构造一个unordered_map存储nums1的所有非重复元素,然后查村nums2的元素是否重复出现于该unordered_set中。注意掌握unordered_set的定义构造,查找,插入和删除 。

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> resultSet;
        unordered_set<int> numSet(nums1.begin(), nums1.end());
        for(int num : nums2){
            if(numSet.find(num) != numSet.end())
                resultSet.insert(num);
        }
        return vector<int> (resultSet.begin(), resultSet.end());

    }
};

Leetcode 202 快乐数

先求数字每位的平方和,然后存储计算过的平方和,检测到已经存储过说明进入了无限循环,返回false。需要注意计算每位的平方和,需要使用取余%不断取出个位数。

class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> sumSet;
        while(1){
            int sum = 0;
            while(n){
                sum += (n % 10) * (n % 10);
                n /= 10;
            }
            
            if(sum == 1){
                return true;
            }
            if(sumSet.find(sum) != sumSet.end()){
                break;
            }
            else{
                sumSet.insert(sum);
            }
            n = sum;
        }
        return false;
    }
};

Leetcode 1 两数之和

关于哈希表需要明确四个问题:1. 为什么要使用哈希表:哈希表用于检查某个元素是否出现过或者存在于某个集合中,因为可以按key索引,比如检测“种类”;2. 用数组,set,还是map:首先判断,元素是否已知有限,如果否则不能使用数组,且如果数组元素少,哈希值很大会浪费内存。set只存储key,map存储key-value;3. map用于存储什么; 4. key-value分别存储什么。

此题还要注意unordered_map的声明,插入unordered_map.insert(pair<int, int>(key, value))

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> record;
        for(int i = 0; i < nums.size(); i++){
            auto iter = record.find(target - nums[i]);
            if(iter != record.end()){
                return {i, iter -> second};
            }
            else{
                record.insert(pair<int, int>(nums[i], i));
            }
        }
        return {};
    }
};

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
第二十二天的算法训练营主要涵盖了Leetcode题目中的三道题目,分别是Leetcode 28 "Find the Index of the First Occurrence in a String",Leetcode 977 "有序数组的平方",和Leetcode 209 "长度最小的子数组"。 首先是Leetcode 28题,题目要求在给定的字符串中找到第一个出现的字符的索引。思路是使用双指针来遍历字符串,一个指向字符串的开头,另一个指向字符串的结尾。通过比较两个指针所指向的字符是否相等来判断是否找到了第一个出现的字符。具体实现的代码如下: ```python def findIndex(self, s: str) -> int: left = 0 right = len(s) - 1 while left <= right: if s[left == s[right]: return left left += 1 right -= 1 return -1 ``` 接下来是Leetcode 977题,题目要求对给定的有序数组中的元素进行平方,并按照非递减的顺序返回结果。这里由于数组已经是有序的,所以可以使用双指针的方法来解决问题。一个指针指向数组的开头,另一个指针指向数组的末尾。通过比较两个指针所指向的元素的绝对值的大小来确定哪个元素的平方应该放在结果数组的末尾。具体实现的代码如下: ```python def sortedSquares(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 ans = [] while left <= right: if abs(nums[left]) >= abs(nums[right]): ans.append(nums[left ** 2) left += 1 else: ans.append(nums[right ** 2) right -= 1 return ans[::-1] ``` 最后是Leetcode 209题,题目要求在给定的数组中找到长度最小的子数组,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值