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

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

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

}; 

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;

    }
};

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

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();
 */

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

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;

    }
};

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

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

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

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

};

521. 最长特殊序列 Ⅰ

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

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

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

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

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);
 */

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

原文地址:https://www.cnblogs.com/corx/p/9001830.html

时间: 2024-10-29 20:58:39

leetcode 刷题录的相关文章

Leetcode刷题录之Two Sum

题意大概是给出一个数列num,和一个目标数target,然后要找出数列中的两个数,使得这两个数之和等于目标数,输出这两个数的下标值(从1开始算). 一个比较暴力的方法是用一个二重循环直接遍历序列,在第一重循环中找到a,在第二重循环中找到b,使得a+b=target,这种做法的时间复杂度是O(n^2), 提交时提示超时. 改进方法,先对数列num复制一个副本,然后对副本进行排序.在一重循环中找到a,接着对这个有序的副本进行二分查找,找到b= target-a,二分查找的 时间复杂度是O(logn)

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

leetcode 刷题之路 63 Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its zig

leetcode 刷题之路 64 Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 给出二叉树的中序遍历和后序遍历结果,恢复出二叉树. 后序遍历序列的最后一个元素值是二叉树的根节点的值,查找该元素在中序遍历序列中的位置mid,根据中序遍历和后序遍历性质,有: 位置mid以前的序列部分为二叉树根节点左子树中

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 题解: 设置两个变量:右边kepler和前向游标forward.如果当前kepeler所指的元素和

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true, as t

【leetcode刷题笔记】Insertion Sort List

Sort a linked list using insertion sort. 题解:实现链表的插入排序. 要注意的地方就是,处理链表插入的时候尽量往当前游标的后面插入,而不要往前面插入,后者非常麻烦.所以每次利用kepeler.next.val和head.val比较大小,而不是kepeler.val和head.val比较大小,因为如果用后者,要把head指向的节点插入到kepeler指向的节点的前面,如果kepeler指向的节点是头结点,就更麻烦了. 代码如下: 1 /** 2 * Defi