备战春招——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;
    }
};
相关推荐
积极向上的向日葵7 分钟前
链表的中间节点
数据结构·算法·链表·快慢指针
曾几何时`23 分钟前
C++——哈希表
算法·哈希算法
Y1nhl39 分钟前
力扣hot100_普通数组_python版本
开发语言·python·算法·leetcode·职场和发展
m0_504135303 小时前
代码随想录算法训练营第六十一天 | floyd算法
算法
xin007hoyo7 小时前
算法笔记.染色法判断二分图
数据结构·笔记·算法
এ᭄画画的北北9 小时前
力扣-234.回文链表
算法·leetcode·链表
八股文领域大手子10 小时前
深入理解缓存淘汰策略:LRU 与 LFU 算法详解及 Java 实现
java·数据库·算法·缓存·mybatis·哈希算法
__lost10 小时前
C++ 解决一个简单的图论问题 —— 最小生成树(以 Prim 算法为例)
算法·图论·最小生成树·prim算法
wuqingshun31415911 小时前
蓝桥杯 11. 打印大X
数据结构·算法·职场和发展·蓝桥杯·深度优先
Blossom.11812 小时前
量子网络:构建未来通信的超高速“高速公路”
网络·opencv·算法·安全·机器学习·密码学·量子计算