0
点赞
收藏
分享

微信扫一扫

HarmonyOS开发(九):数据管理

菜菜捞捞 2023-12-04 阅读 44
算法

哈希表

哈希表主要是使用 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;
    }
};
举报

相关推荐

0 条评论