首页 > 其他 > 详细

3. 查找1

时间:2020-08-26 09:08:03      阅读:156      评论:0      收藏:0      [点我收藏+]

查找表

  • 第一类: 查找有无--set
    元素‘a‘是否存在,通常用set:集合
    set只存储键,而不需要对应其相应的值。
    set中的键不允许重复
  • 第二类: 查找对应关系(键值对应)--dict
    元素‘a‘出现了几次:dict-->字典
    dict中的键不允许重复
  • 第三类: 改变映射关系--map
    通过将原有序列的关系映射统一表示为其他

349 两个数组的交集

技术分享图片

题目分析

可以直接在容器中查找。

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        if(nums1.size()>nums2.size())
            swap(nums1, nums2);
        vector<int> ans;
        int n = nums1.size();
        for(int i=0; i<n; i++){
            if(find(nums2.begin(), nums2.end(), nums1[i]) != nums2.end()){
                if(find(ans.begin(), ans.end(), nums1[i]) == ans.end())
                    ans.push_back(nums1[i]);
            }
        }
        return ans;
    }
};

350. 两个数组的交集II

技术分享图片

题目分析

该题与上题的区别在于,本题的输出允许重复,且出现次数应与该元素在两个数组中出现次数的最小值一致。所以可以选择字典。

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        if(nums1.size() > nums2.size()) 
            return intersect(nums2, nums1); 
        unordered_map<int, int> map;
        for(int i : nums1) map[i] ++;
        vector<int> ans;
        for(int i : nums2) {
            if(map.count(i)) {
                ans.push_back(i);   
                map[i] --;
            }
            if(map[i] == 0) map.erase(i);
        }
        return ans;
    }
};

242. 有效的字母异位词

技术分享图片

题目分析

class Solution {
public:
    bool isAnagram(string s, string t) {
        int hash1[128];
        int hash2[128];
        memset(hash1, 0, sizeof(int) * 128);
        memset(hash2, 0, sizeof(int) * 128);
        for (char c : s) {
            hash1[c - ‘0‘] ++;
        }
        for (char c : t) {
            hash2[c - ‘0‘] ++;
        }
        for (int i = 0; i < 128; i ++) {
            if (hash1[i] != hash2[i]) {
                return false;
            }
        }
        return true;
    }
};

202 快乐数

技术分享图片

题目分析

当n不等于1时就循环,每次循环时,将其最后一位到第一位的数依次平方求和,比较求和是否为1。

class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> hh;
        while(!hh.count(n)){
            int sum = 0;
            hh.insert(n);
            while(n != 0){
                sum = sum + (n%10) * (n%10);
                n /= 10;
            }
            n = sum;
        }
        return n == 1;
    }
};

3. 查找1

原文:https://www.cnblogs.com/Just-Rejoice/p/13562856.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!