美文网首页
LC560/LC138如何机智正确地使用map

LC560/LC138如何机智正确地使用map

作者: 锦绣拾年 | 来源:发表于2020-05-15 16:59 被阅读0次

    LC138 复制链表

    给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
    
    要求返回这个链表的 深拷贝。 
    
    我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
    
    val:一个表示 Node.val 的整数。
    random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为  null 。
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    /*
    // Definition for a Node.
    class Node {
    public:
        int val;
        Node* next;
        Node* random;
        
        Node(int _val) {
            val = _val;
            next = NULL;
            random = NULL;
        }
    };
    */
    
    class Solution {
    public:
        Node* copyRandomList(Node* head) {
            if(!head)
                return NULL;
            Node* y=new Node(head->val);
            Node* cur=head;
            Node* ycu=y;
            map<Node*,Node*> tmp;
            tmp[head]=y;
            while(cur->next){
                ycu->next=new Node(cur->next->val);
                tmp[cur->next]=ycu->next;
                ycu=ycu->next;
                cur=cur->next;
            }
            
            cur=head;
            ycu=y;
            while(cur){
                if(cur->random){
                    ycu->random=tmp[cur->random];
                }
                cur=cur->next;
                ycu=ycu->next;
            }
            return y;
            
        }
    };
    

    LC560

    给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
    
    示例 1 :
    
    输入:nums = [1,1,1], k = 2
    输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
    说明 :
    
    数组的长度为 [1, 20,000]。
    数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/subarray-sum-equals-k
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    
    class Solution {
    public:
        int subarraySum(vector<int>& nums, int k) {
            //理解一下前缀和概念
            //求前缀和 然后=k即 pre[i]-pre[j]=k。用map,看map[pre[i]-k]是否有值,即是否有这个前缀和
            //map装的是此时前缀以及对应的次数
            map<int,int> res;
            res[0]=1;
            // res.insert(make_pair(0,1));
            int sum=0;
            int count=0;
            for(int i=0;i<nums.size();i++){
                sum+=nums[i];
                
                // cout<<sum<<res[sum]<<endl;
                if(res.find(sum-k)!=res.end()){//本来写sum>=k,但其实可能有负数
                    count+=res[sum-k];
                    // cout<<sum-k<<endl;
                }
                res[sum]+=1;//可以直接这样吗 需要判断吗,这一级要放在后面,防止算入自己
            }
            return count;
    
        }
    };
    

    相关文章

      网友评论

          本文标题:LC560/LC138如何机智正确地使用map

          本文链接:https://www.haomeiwen.com/subject/hathohtx.html