复制代码

leetcode 刷题录

 

11. 盛最多水的容器

class Solution {
public:
    int maxArea(vector<int>& height) {
       vector<int> & v =height;
       int l =0,r=v.size()-1;
       int res = 0;
        while(l<r)
        {
           int lval = v[l];
           int rval = v[r];
           int minval = min(lval,rval);
           res =max(res,minval*(r-l));
           if(lval<rval) l++;
           else r--; 
        }
       return res ;
    }
};
View Code

 

34. 搜索范围

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> v(2,-1);
        int high =binarySearchUp(nums,target,0,nums.size()-1);
    
        int low =binarySearchDown(nums,target,0,nums.size()-1);
        //DBG2(high,low);

        if(high >= low )
        {
            v[0]=low;
            v[1]=high;
        }
 
        return v;
    }
private:
 
    int binarySearchUp(vector<int> & nums ,int target,int begin,int end)
    {
        if(begin>end)return end;
        int mid =(begin+end) >>1;
        if(nums[mid]>target) return binarySearchUp(nums,target,begin,mid-1);
        else return binarySearchUp(nums,target,mid+1,end);    

    }   
    int binarySearchDown(vector<int> & nums  ,int target,int begin,int end)
    {
        if(begin>end)return begin;
        int mid =(begin+end) >>1;
        if(nums[mid]<target) return binarySearchDown(nums,target,mid+1,end);    
        else return binarySearchDown(nums,target,begin,mid-1);
    }
};
View Code

 

 59. 螺旋矩阵 II

 
class Solution {
public: 
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> > v (n,vector<int> (n,0)); 
        int col_min=0,col_max=n-1,row_min=0,row_max=n-1;
        int row=-1,col=0;
        int i=1;
        while(i<=n*n)
        {
            while(++row<=row_max){ 
                v[col][row]=i++; 
         
            }
              row--; 
      
            while(++col<=col_max) {
                v[col][row]=i++; 
             
            }
              col --; row_max--;
            while(--row>=row_min) {
                v[col][row]=i++; 
                 
            }     row++;  col_max--; col_min++;
            while(--col>=col_min) {
                v[col][row]=i++;
             
            }   col++;row_min++; 
   
        } 
        return v;
    }
   
}; 
View Code

 

 60. 第k个排列

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int> v;
        for(int i=1;i<=n;i++) v.push_back(i);
        for(int i=0;i<k;i++)
        {
            next_permutation(v.begin(),v.end());  
        };
        string str ="";
        for(auto i :v)
        {
            str+=i;
        }
        return str;
        
        
    }
};
View Code

80. 删除排序数组中的重复项 II

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
          int n =nums.size();
        int k=-1,t = 0,pos =0;
        for(int i=0;i<n;i++)
        {
            if(nums[i]==k && t<2)
            {
                nums[pos++] = nums[i];
                t++;
            }
            else if(nums[i]!=k)
            {
                t=1;
                nums[pos++]=nums[i];
                k=nums[i];
            }
        }
        
        return pos;
    }
};
View Code

 

 

141. 环形链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL) return false;
        ListNode * fast=head,*last=head;
        if(fast->next&& fast->next->next) fast =fast->next->next;
        else return false ;
        if(last->next)last=last->next;
        while(fast!=last)
        {
            if(fast->next&& fast->next->next) fast =fast->next->next;
            else return false ;
            if(last->next)last=last->next;
        }
        return true;
    }
};
View Code

 

155. 最小栈

class MinStack {
public: 
    /** initialize your data structure here. */
    stack<int>all;
    stack<int>minstack;
    MinStack() {
        
    }
    
    void push(int x) {
        if(all.empty())
        {
            all.push(x);
            minstack.push(x);
        }
        else 
        {
            all.push(x);
            if(minstack.top()>=x)minstack.push(x);;
        }
    }
    
    void pop() {
        if(all.top()==minstack.top()) minstack.pop();
        all.pop();
    }
    
    int top() {
        return all.top();
    }
    
    int getMin() {
     
      return   minstack.top(); 
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */
View Code

 414. 第三大的数

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        int m1=INT_MIN,m2=INT_MIN,m3=INT_MIN;
        bool flag=true;
        for(auto i:nums)
        {
            if(i==INT_MIN) flag=false;
            if(m1==i||m2==i||m3==i)continue;
            if(m1==INT_MIN|| i >m1)
            {
                m3=m2;
                m2=m1;
                m1=i;
            }
            else if(m2==INT_MIN||i>m2)
            {
                m3=m2;
                m2=i;
            }
            else if(m3==INT_MIN||i>m3)
            {
                m3=i;
            }
        } 
        if(flag) return (m3 == INT_MIN) ? m1 : m3;
        else if(m2==INT_MIN||m1==INT_MIN) return m1;
        else return INT_MIN;
    }
};
View Code

 

416. Partition Equal Subset Sum

class Solution {
public:
    bool canPartition(vector<int>& nums) {
        int sum = accumulate(nums.begin(), nums.end(), 0), target = sum >> 1;
        if (sum & 1) return false;
        vector<bool> dp(target + 1, false);
        dp[0] = true;
        for (int num : nums) {
            for (int i = target ; i >=num ; --i) {
                dp[i] = dp[i] || dp[i - num];
            }
        }
        return dp[target];
    }
};
View Code

 354. 俄罗斯套娃信封问题

class Solution {
public:
    int maxEnvelopes(vector<pair<int, int>>& envelopes) {
     #if 0 //会产生 HANK 
        sort(envelopes.begin(),envelopes.end(),
             [](pair<int,int> & l,pair<int,int> &r )
             {   if(l.first == r.first) return l.second<r.second; 
              else return l.first<r.first;
             } );
        pair<int,int> *  t = NULL;
        int n =0 ;
        int n_size = envelopes.size();
        for(int i =0;i<n_size;i++)
        {
            if(t==NULL)
            {
                t=&envelopes[i];
                n++;
            }
            else 
            {
                  if(t->first <envelopes[i].first && t->second <envelopes[i].second)
                   n++,t=&envelopes[i];
            }
        }
      
        return n;
        #endif
        vector<int> v(envelopes.size(),1);
        sort(envelopes.begin(),envelopes.end());
        int res = 0;
        int n = envelopes.size();
        for(int i =0;i<n;i++)
        {
            for(int j = 0;j<i;j++)
            {
                if(envelopes[i].first > envelopes[j].first &&  envelopes[i].second > envelopes[j].second)
                    v[i]=max(v[i],v[j]+1);
            }
            res =max(res,v[i]);
        }
        return res;
    }
};
View Code

 

373. 查找和最小的K对数字

class Solution {
public:
    vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
        vector<pair<int,int>> v;
        for(auto i : nums1) for(auto j: nums2)
            v.push_back(make_pair(i,j));
        sort(v.begin(),v.end(),[](pair<int,int>& l,pair<int,int>& r)
             {
                 return l.first+l.second<r.first+r.second ; 
             });
     
        if(v.size()>k)v.erase(v.begin()+k,v.end());
        return v;
    }
};
View Code

 

374. 猜数字大小

// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
    int guessNumber(int n) {
       int l=1,r=n;
        int mid,ret;
        while(l<r)
        {
           mid = l/2+r/2;
            // mid=l+r>>1;
            ret = guess(mid);
            if(ret==0) return mid;
            else if(ret< 0 ) r=mid-1;
            else l=mid+1;
        }
        return l;
     
    }
};
View Code

 

 378. 有序矩阵中第K小的元素

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        priority_queue<int> q ;
        for(auto & v : matrix) for(auto i:v)
        {
          q.push(i);
          if(q.size()>k)q.pop();
          
        } return q.top();
    }
};
View Code

 

383. 赎金信

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
      // unordered_map<char,int> a;
        int a[256] ={0};
        for(auto i:magazine)
        {
             
            a[i]++;
        }
        for(auto i:ransomNote)
       
        {
            
            if(a[i]> 0 ) a[i]--;
            else return false;

        }
            return true;
    }
};
View Code

 

395. 至少有K个重复字符的最长子串

View Code

 

 515. 在每个树行中找最大值

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        vector<int> v;
        if(root==NULL) return v;
        queue<TreeNode*> q ;
        q.push(root);
        
        while(1)
        {
            int tmp = getnum(q);
            v.push_back(tmp);
            getnxt(q) ;
            if(q.empty())break;            
        }
        return v;
    }
    void  getnxt(queue<TreeNode*>&  tmp )
    {
        queue<TreeNode*> t ;
        while(!tmp.empty())
        {
            TreeNode* i=tmp.front();
            if(i->left)
            {
                t.push(i->left);
            }
            if(i->right)
            {
                t.push(i->right);
            } 
             tmp.pop();
        }
      
        while(!t.empty()) tmp.push(t.front()),t.pop();
    }
    int getnum(queue<TreeNode*>  tmp)
    {
        int mm = -2147483648;
         while(!tmp.empty())
        {
            int  tt = tmp.front()->val; 
            mm=max(mm,tt);
            tmp.pop();
        }
        return mm;
    }
    
};
View Code

 

 

521. 最长特殊序列 Ⅰ

class Solution {
public:
    int findLUSlength(string a, string b) {
        return a==b?-1:max(a.size(),b.size());
    }
};
View Code

 

540. 有序数组中的单一元素 

class Solution {
public:
    int singleNonDuplicate(vector<int>& nums) {
        int ans =0;
        for(auto i:nums)
            ans^=i;
        return ans;
    }
};
View Code

 

 

 639. 解码方法 2

class Solution {
public:
     int ways(char c) {  
        if (c == '*')  
            return 9;  
        if (c == '0')  
            return 0;  
        return 1;  
    }  
    int ways(char i, char j) {  
        if (i == '*' && j == '*')  
            return 15;  
        if (i == '*')  
            return (j <= '6' ? 2 : 1);  
        if (j == '*') {  
            if (i == '1')  
                return 9;  
            if (i == '2')  
                return 6;  
            return 0;  
        }  
        if (i == '1' || (i == '2' && j <= '6'))  
            return 1;  
        return 0;  
    }  
    int numDecodings(string s) {
        int  n =s.length();
        if(n==0||s[0]=='0') return 0;
        long f2=1,f1= (long)ways(s[0]);
        long res = f1;
        long mod = (long)1e9+7;
        for(int i=1;i<n;i++)
        {
            res = ways(s[i-1],s[i])*f2 + ways(s[i])*f1;
            res%=mod;
            f2=f1;
            f1= res;
        }
        return res;
    }
};
View Code

 

 

677. 键值映射

class MapSum {
public:
    /** Initialize your data structure here. */
    map<string,int> m;
    
    MapSum() {
        
    }
    
    void insert(string key, int val) {
        m[key] =val;
       
    }
    
    int sum(string prefix) {
           int s = 0;
        for (auto one : m)
        {
            if (prefix == one.first.substr(0, prefix.length()))
                s += one.second;
        }
        return s;
    }
};

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum obj = new MapSum();
 * obj.insert(key,val);
 * int param_2 = obj.sum(prefix);
 */
View Code

 743. 网络延迟时间

#define REP(i,l,r) for(int i=l;i<=r;i++)
class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
       const int inf = (int)1e5+9;
       int n=N,k=K;
       int m[n+1][n+1];
       int dist[n+1],vis[n+1];
       REP(i,1,n) REP(j,1,n) if(i==j)m[i][j] ;else m[i][j]=inf;
       for(auto i:times)m[i[0]][i[1]]=i[2];
       REP(i,1,n) dist[i]=m[k][i],vis[i]=0;
       vis[k]=1;
        int ans =-1;
       REP(i,1,n-1)
       {
           int minx=inf,u=k;
           REP(j,1,n) if(!vis[j] && dist[j]!=inf &&dist[j]<minx) minx=dist[j],u=j;
           if(minx==inf) return -1;
           vis[u]=1;
           ans=max(ans,minx);
           REP(j,1,n) if(!vis[j]&& dist[j]>dist[u]+m[u][j])
               dist[j]=dist[u]+m[u][j];
        
        }
        return ans;
    }
};
View Code

 

 

 

posted @ 2018-05-21 23:38  pg633  阅读(132)  评论(0编辑  收藏  举报