[Basic Data Structure] 5.8 Task

basic data structure

Leetcode.1 Sum of two numbers
Leetcode.187 Repeated DNA sequence
Leetcode.706 Design a hash map
Leetcode.652 Find repeated subtrees
Leetcode.560 Sum of K subarrays
Leetcode.547 Number of provinces
Leetcode.684 Redundant connections
Leetcode .692The median of the top K high-frequency wordsLeetcode.295The
data streamLeetcode.352Turn
the data stream into multiple disjoint intervals

1. Leetcode.1 Sum of two numbers

Given an integer array nums and an integer target value target, please find the two integers in the array whose sum is the target value target and return their array subscripts.

You can assume that each input will correspond to only one answer. However, the same element in the array cannot appear repeatedly in the answer.

You can return answers in any order.

  vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int>hash;
        for(int i=0;i<nums.size();i++){
            if(hash.count(target-nums[i]))return {hash[target-nums[i]],i};
            hash[nums[i]]=i;
        }
        return {-1,-1};
    }

2. Leetcode.187 repeated DNA sequence

A DNA sequence consists of a series of nucleotides, abbreviated as 'A', 'C', 'G' and 'T'.

For example, "ACGAATTCCG" is a DNA sequence.
When studying DNA, it is very useful to identify repeating sequences in DNA.

Given a string s representing a DNA sequence, return all sequences (substrings) of length 10 that appear more than once in the DNA molecule. You can return answers in any order.

  vector<string> findRepeatedDnaSequences(string s) {
        unordered_map<string,int>hash;
        vector<string>ans;
        for(int i=0;i+9<=s.size()-1;i++){
            string str=s.substr(i,10);
            hash[str]++;
            if(hash[str]==2)ans.push_back(str);
        }
        return ans;
    }

3. Leetcode.706 design hash map

Design a hash map (HashMap) without using any built-in hash table library.

  int N=20011;
    vector<list<pair<int,int>>>h;
    MyHashMap() {
        h=vector<list<pair<int,int>>>(N);
    }
    list<pair<int,int>>::iterator find(int key){
        int t=key%N;
        for(auto it=h[t].begin();it!=h[t].end();it++){
            if(it->first==key)return it;
        }
        return h[t].end();
    }
    void put(int key, int value) {
        auto it=find(key);
        int t=key%N;
        if(it==h[t].end())h[t].push_back({key,value});
        else it->second=value;
    }
    
    int get(int key) {
        auto it=find(key);
        int t=key%N;
        if(it==h[t].end())return -1;
        else return it->second;
    }
    
    void remove(int key) {
        auto it=find(key);
        int t=key%N;
        if(it==h[t].end())return;
        else h[t].erase(it);
    }

4. Leetcode.652 finds duplicate subtrees

Given a binary tree root, return all duplicate subtrees.

For duplicate subtrees of the same type, you only need to return the root node of any one of them.

Two trees are duplicates if they have the same structure and the same node values.

  unordered_map<string,int>h;
    vector<TreeNode*>ans;
    //1,2, , ,    
    string dfs(TreeNode*root){
        if(root==NULL)return "";
        string str="";
        str+=to_string(root->val)+",";
        str+=dfs(root->right)+",";
        str+=dfs(root->left);
        h[str]++;
        if(h[str]==2)ans.push_back(root);
        
        return str;
    }
    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
        dfs(root);
        return ans;
    }

5. The sum of Leetcode.560 is K subarray

Given an integer array nums and an integer k, please count and return the number of subarrays in the array whose sum is k.

  int subarraySum(vector<int>& nums, int k) {
        unordered_map<int,int>h;
        int sum=0;
        h[0]=1;
        int ans=0;
        for(int i=0;i<nums.size();i++){
            sum+=nums[i];
            ans+=h[sum-k];
            h[sum]++;
        }
        return ans;
    }

6. Number of provinces in Leetcode.547

There are n cities, some of them are connected to each other and some are not. If city a is directly connected to city b, and city b is directly connected to city c, then city a is indirectly connected to city c.

A province is a group of directly or indirectly connected cities, excluding other unconnected cities.

Give you an nxn matrix isConnected, where isConnected[i][j] = 1 means that the i-th city and the j-th city are directly connected, and isConnected[i][j] = 0 means that the two are not directly connected.

Returns the number of provinces in the matrix.

  vector<int>p;
    int find(int x){
        if(x!=p[x])p[x]=find(p[x]);
        return p[x];
    }
    int findCircleNum(vector<vector<int>>& isConnected) {
        int n=isConnected.size();
        p=vector<int>(n);
        for(int i=0;i<n;i++)p[i]=i;
        int ans=n;
        for(int i=0;i<n;i++){
            for(int j=0;j<i;j++){
                if(isConnected[i][j]==0)continue;
                if(find(i)!=find(j)){
                    p[find(i)]=find(j);
                    ans--;
                }
            }
        }
        return ans;
    }

7. Leetcode.684 redundant connection

A tree can be viewed as a connected and acyclic undirected graph.

Given the graph after adding an edge to a tree with n nodes (node ​​values ​​1~n). The two vertices of the added edge are contained between 1 and n, and this additional edge does not belong to an existing edge in the tree. The information of the graph is recorded in the two-dimensional array edges of length n. edges[i] = [ai, bi] means that there is an edge between ai and bi in the graph.

Please find an edge that can be deleted so that the remaining part is a tree with n nodes. If there are multiple answers, return the last edge in the array edges.

  vector<int>p;
    int find(int x){
        if(x!=p[x])p[x]=find(p[x]);
        return p[x];
    }
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        int n=edges.size();
        p=vector<int>(n+1);
        for(int i=i;i<=n;i++)p[i]=i;
        for(auto e:edges){
            int x=e[0];
            int y=e[1];
            if(find(x)==find(y))return {x,y};
            p[find(x)]=find(y);
        }
        return {-1,-1};
    }

8. The first K high-frequency words of Leetcode.692

Given a word list words and an integer k, return the top k most frequently occurring words.

The answers returned should be sorted by word frequency from high to low. If different words have the same frequency, sort them lexicographically.

  unordered_map<string,int>hash;
    typedef pair<int,string> PIS;
    priority_queue<PIS>heap;
    vector<string> topKFrequent(vector<string>& words, int k) {
        for(int i=0;i<words.size();i++){
            hash[words[i]]++;
        }
        for(auto item:hash){
            PIS t(-item.second,item.first);
            heap.push(t);
            //cout<<item.second<<item.first<<endl;
            if(heap.size()>k){
                //cout<<heap.top().second<<endl;
                heap.pop();
            }
        }
        vector<string>ans(k);
        for(int i=k-1;i>=0;i--){
            ans[i]=heap.top().second;
            //cout<<ans[k]
            heap.pop();
        }
        return ans;
    }

9. Median of Leetcode.295 data stream

The median is the number in the middle of an ordered list. If the list length is an even number, the median is the average of the two middle numbers.

  priority_queue<int>down;
    priority_queue<int,vector<int>,greater<int>>up;
    MedianFinder() {

    }
    
    void addNum(int num) {
        if(down.empty()||num>=down.top())up.push(num);
        else{
            down.push(num);
            up.push(down.top());
            down.pop();
        }
        if(up.size()>down.size()+1){
            down.push(up.top());
            up.pop();
        }
    }
    
    double findMedian() {
        if(down.size()+up.size()&1==1)return up.top();
        else return (down.top()+up.top())/2.0;
    }

10. Leetcode.352 turns the data stream into multiple disjoint intervals

Given a data stream input consisting of non-negative integers a1, a2, …, an, ask you to summarize the numbers you have seen so far into a list of disjoint intervals.

Implement the SummaryRanges class:

SummaryRanges() initializes the object with an empty data stream.
void addNum(int val) adds integer val to the data stream.
int[][] getIntervals() Returns a summary of the integers in the data stream as a list of disjoint intervals [starti, endi].

  map<int, int> interval;
    SummaryRanges() {}
    void addNum(int val) {
        auto up = interval.upper_bound(val);
        auto down = (up == interval.begin() ? interval.end() : prev(up));

        if (down != interval.end() && (val >= down->first && val <= down->second)) {

        } else if ((up != interval.end() && up->first - 1 == val) && (down != interval.end() && down->second + 1 == val)) {
            int l = down->first, r = up->second;
            interval.erase(down->first);
            interval.erase(up->first);
            interval.emplace(l, r);
        } else if (down != interval.end() && down->second + 1 == val) {
            int l = down->first, r = val;
            interval.erase(l);
            interval.emplace(l, r);
        } else if (up != interval.end() && up->first - 1 == val) {
            int l = val, r = up->second;
            interval.erase(up->first);
            interval.emplace(l, r);
        } else {
            interval.emplace(val, val);
        }
        cout << interval.size() << endl;

    }

    vector<vector<int>> getIntervals() {
        vector<vector<int>> ans;
        for (auto& it : interval) {
            ans.push_back({it.first, it.second});
        }
        return ans;
    }

Guess you like

Origin blog.csdn.net/Peanut31434331/article/details/124655363