备战春招——12.3 算法

2023-12-05

哈希表

哈希表主要是使用 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,标志位方法,用一个记录上一个出现的位置,从那里开始新的暴力操作。

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;
    }
};



环形链表

在这里插入图片描述

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;
    }
};

相交链表

在这里插入图片描述

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;
    }
};

快乐数

在这里插入图片描述

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;
    }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

备战春招——12.3 算法 的相关文章

  • 前端分片上传

    前端分片上传是一种将大文件分成若干个小块进行上传的方式 以解决大文件上传时网络不稳定或上传速度慢的问题 下面是前端分片上传的基本步骤 使用JavaScript读取文件 将文件分成若干块 可以使用File API来实现这个功能 使用XMLHt

随机推荐