备战春招——12.3 算法

哈希表

哈希表主要是使用 map、unordered_map、set、unorerdered_set、multi_,完成映射操作,主要是相应的函数。map和set是有序的,使用的是树的形式,unordered_map和unordered_set使用的是散列比表的,无序。

相应函数

set multiset

相应的地址

map multimap

相应地址

unordered_map unordered_multimap

相应位置

unordered_set unordered_multiset

相应地址

刷题

无重复字符的最长子串

暴力的哈希操作,最露比的方法,肯定可以优化的,emm,标志位方法,用一个记录上一个出现的位置,从那里开始新的暴力操作。

cpp 复制代码
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
       int  n = s.length();
       int m = 0;
       set<char> mp;
       //最露的方法,相当于暴力哈哈
        for(int i=0;i<n;i++){   
            mp.clear();
            int index = 0;
            for(int j=i;j<n;j++){
                if(mp.find(s[j])==mp.end()){
                    mp.insert(s[j]);
                    index++;
                }else{
                    break;
                }
            }
            if(index>m) m=index;
        }
        return m;
    }
};

环形链表

cpp 复制代码
class Solution {
public:
    bool hasCycle(ListNode *head) {
        set<ListNode*> s;
        while(head!=NULL){
            if(s.find(head)!=s.end()){
                return true;
            }
            s.insert(head);
            head = head->next;
        } 
        return false;
    }
};

相交链表

cpp 复制代码
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {

       set<ListNode*> d;

        while(headA!=NULL){
            d.insert(headA);
            headA=headA->next;
        }
        while(headB){
            if(d.find(headB)!=d.end()){
                return headB;
            }
            headB=headB->next;
        }
        return NULL;
    }
};

快乐数

cpp 复制代码
class Solution {
public:
    bool isHappy(int n) {
        set<int> d;
     
        while(true){
            d.insert(n);
            if(n==1)break;
            int sum = 0;
            while(n){
                int d = n%10;
                n/=10;
                sum +=d*d;
            }
            n=sum;
            if(d.find(n)!=d.end()){
                return false;
            }

        }
        return true;
    }
};
相关推荐
BothSavage5 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn5 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽7 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术1 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六1 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程
胡萝卜术1 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
Asize1 天前
初识DFS 与 BFS:递归、队列与图遍历
算法