zoukankan      html  css  js  c++  java
  • Leetcode中值得一做的题

    3.longest substring

    Given a string, find the length of the longest substring without repeating characters.

    Examples:

    Given "abcabcbb", the answer is "abc", which the length is 3.

    Given "bbbbb", the answer is "b", with the length of 1.

    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

    4. Median of Two Sorted Arrays

    There are two sorted arrays nums1 and nums2 of size m and n respectively.

    Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

    Example 1:

    nums1 = [1, 3]
    nums2 = [2]
    
    The median is 2.0
    

    Example 2:

    nums1 = [1, 2]
    nums2 = [3, 4]
    
    The median is (2 + 3)/2 = 2.5

    存在log(min(n,m))的解法

    这个代码太复杂了,现场不容易想起来,看这个:链接

    This problem is notoriously hard to implement due to all the corner cases. Most implementations consider odd-lengthed and even-lengthed arrays as two different cases and treat them separately. As a matter of fact, with a little mind twist. These two cases can be combined as one, leading to a very simple solution where (almost) no special treatment is needed.
    
    First, let's see the concept of 'MEDIAN' in a slightly unconventional way. That is:
    
    "if we cut the sorted array to two halves of EQUAL LENGTHS, then
    median is the AVERAGE OF Max(lower_half) and Min(upper_half), i.e. the
    two numbers immediately next to the cut".
    For example, for [2 3 5 7], we make the cut between 3 and 5:
    
    [2 3 / 5 7]
    then the median = (3+5)/2. Note that I'll use '/' to represent a cut, and (number / number) to represent a cut made through a number in this article.
    
    for [2 3 4 5 6], we make the cut right through 4 like this:
    
    [2 3 (4/4) 5 7]
    
    Since we split 4 into two halves, we say now both the lower and upper subarray contain 4. This notion also leads to the correct answer: (4 + 4) / 2 = 4;
    
    For convenience, let's use L to represent the number immediately left to the cut, and R the right counterpart. In [2 3 5 7], for instance, we have L = 3 and R = 5, respectively.
    
    We observe the index of L and R have the following relationship with the length of the array N:
    
    N        Index of L / R
    1               0 / 0
    2               0 / 1
    3               1 / 1  
    4               1 / 2      
    5               2 / 2
    6               2 / 3
    7               3 / 3
    8               3 / 4
    It is not hard to conclude that index of L = (N-1)/2, and R is at N/2. Thus, the median can be represented as
    
    (L + R)/2 = (A[(N-1)/2] + A[N/2])/2
    To get ready for the two array situation, let's add a few imaginary 'positions' (represented as #'s) in between numbers, and treat numbers as 'positions' as well.
    
    [6 9 13 18]  ->   [# 6 # 9 # 13 # 18 #]    (N = 4)
    position index     0 1 2 3 4 5  6 7  8     (N_Position = 9)
              
    [6 9 11 13 18]->   [# 6 # 9 # 11 # 13 # 18 #]   (N = 5)
    position index      0 1 2 3 4 5  6 7  8 9 10    (N_Position = 11)
    As you can see, there are always exactly 2*N+1 'positions' regardless of length N. Therefore, the middle cut should always be made on the Nth position (0-based). Since index(L) = (N-1)/2 and index(R) = N/2 in this situation, we can infer that index(L) = (CutPosition-1)/2, index(R) = (CutPosition)/2.
    
    Now for the two-array case:
    
    A1: [# 1 # 2 # 3 # 4 # 5 #]    (N1 = 5, N1_positions = 11)
    
    A2: [# 1 # 1 # 1 # 1 #]     (N2 = 4, N2_positions = 9)
    Similar to the one-array problem, we need to find a cut that divides the two arrays each into two halves such that
    
    "any number in the two left halves" <= "any number in the two right
    halves".
    We can also make the following observations:
    
    There are 2N1 + 2N2 + 2 position altogether. Therefore, there must be exactly N1 + N2 positions on each side of the cut, and 2 positions directly on the cut.
    
    Therefore, when we cut at position C2 = K in A2, then the cut position in A1 must be C1 = N1 + N2 - k. For instance, if C2 = 2, then we must have C1 = 4 + 5 - C2 = 7.
    
     [# 1 # 2 # 3 # (4/4) # 5 #]    
    
     [# 1 / 1 # 1 # 1 #]   
    When the cuts are made, we'd have two L's and two R's. They are
    
     L1 = A1[(C1-1)/2]; R1 = A1[C1/2];
     L2 = A2[(C2-1)/2]; R2 = A2[C2/2];
    In the above example,
    
        L1 = A1[(7-1)/2] = A1[3] = 4; R1 = A1[7/2] = A1[3] = 4;
        L2 = A2[(2-1)/2] = A2[0] = 1; R2 = A1[2/2] = A1[1] = 1;
    Now how do we decide if this cut is the cut we want? Because L1, L2 are the greatest numbers on the left halves and R1, R2 are the smallest numbers on the right, we only need
    
    L1 <= R1 && L1 <= R2 && L2 <= R1 && L2 <= R2
    to make sure that any number in lower halves <= any number in upper halves. As a matter of fact, since
    L1 <= R1 and L2 <= R2 are naturally guaranteed because A1 and A2 are sorted, we only need to make sure:
    
    L1 <= R2 and L2 <= R1.
    
    Now we can use simple binary search to find out the result.
    
    If we have L1 > R1, it means there are too many large numbers on the left half of A1, then we must move C1 to the left (i.e. move C2 to the right); 
    If L2 > R1, then there are too many large numbers on the left half of A2, and we must move C2 to the left.
    Otherwise, this cut is the right one. 
    After we find the cut, the medium can be computed as (max(L1, L2) + min(R1, R2)) / 2;
    Two side notes:
    
    A. since C1 and C2 can be mutually determined from each other, we might as well select the shorter array (say A2) and only move C2 around, and calculate C1 accordingly. That way we can achieve a run-time complexity of O(log(min(N1, N2)))
    
    B. The only edge case is when a cut falls on the 0th(first) or the 2Nth(last) position. For instance, if C2 = 2N2, then R2 = A2[2*N2/2] = A2[N2], which exceeds the boundary of the array. To solve this problem, we can imagine that both A1 and A2 actually have two extra elements, INT_MAX at A[-1] and INT_MAX at A[N]. These additions don't change the result, but make the implementation easier: If any L falls out of the left boundary of the array, then L = INT_MIN, and if any R falls out of the right boundary, then R = INT_MAX.
    
    I know that was not very easy to understand, but all the above reasoning eventually boils down to the following concise code:
    
     double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int N1 = nums1.size();
        int N2 = nums2.size();
        if (N1 < N2) return findMedianSortedArrays(nums2, nums1);    // Make sure A2 is the shorter one.
        
        if (N2 == 0) return ((double)nums1[(N1-1)/2] + (double)nums1[N1/2])/2;  // If A2 is empty
        
        int lo = 0, hi = N2 * 2;
        while (lo <= hi) {
            int mid2 = (lo + hi) / 2;   // Try Cut 2 
            int mid1 = N1 + N2 - mid2;  // Calculate Cut 1 accordingly
            
            double L1 = (mid1 == 0) ? INT_MIN : nums1[(mid1-1)/2];    // Get L1, R1, L2, R2 respectively
            double L2 = (mid2 == 0) ? INT_MIN : nums2[(mid2-1)/2];
            double R1 = (mid1 == N1 * 2) ? INT_MAX : nums1[(mid1)/2];
            double R2 = (mid2 == N2 * 2) ? INT_MAX : nums2[(mid2)/2];
            
            if (L1 > R2) lo = mid2 + 1;        // A1's lower half is too big; need to move C1 left (C2 right)
            else if (L2 > R1) hi = mid2 - 1;    // A2's lower half too big; need to move C2 left.
            else return (max(L1,L2) + min(R1, R2)) / 2;    // Otherwise, that's the right cut.
        }
        return -1;
    } 
    If you have any suggestions to make the logic and implementation even more cleaner. Please do let me know!
    View Code

    11. Container With Most Water

    主要是一个贪心的思想,从小边往里面靠

    18. 4Sum

    2 Sum, 3 Sum的加强版

     1 class Solution {
     2 public:
     3     vector<vector<int>> fourSum(vector<int>& nums, int target) {
     4         int n=nums.size();
     5         sort(nums.begin(),nums.end());
     6         int i,j,k;
     7         int f1=0,f2=0,f3=0;
     8         int b1=0,b2=0,b3=0;
     9         vector<vector<int>> fans;
    10         int tot=0;
    11         for(i=0;i<n;i++){
    12             int w1=target-nums[i];
    13             for(j=i+1;j<n;j++){
    14                 int w2=w1-nums[j];
    15                 f1=j+1;
    16                 b1=n-1;
    17                 while(f1<b1){
    18                     int sum=nums[f1]+nums[b1];
    19                     if(sum==w2){  //符合要求
    20                         vector<int> ans(4,0);
    21                         ans[0]=nums[i];
    22                         ans[1]=nums[j];
    23                         ans[2]=nums[f1];
    24                         ans[3]=nums[b1];
    25                         fans.push_back(ans);
    26                         while(f1<b1&&ans[2]==nums[f1])  f1++;       //相同的可以不算进去了
    27                         while(f1<b1&&ans[3]==nums[f1])  b1--;
    28                     }
    29                     else if(sum<w2){
    30                         f1++;
    31                     }
    32                     else b1--;
    33                 }
    34                 while(j + 1 <n && nums[j + 1] == nums[j]) ++j;
    35             }
    36             while (i + 1 <n && nums[i + 1] == nums[i]) ++i;
    37         }
    38         return fans;
    39     }
    40 };
    View Code

    快速排序,第k小的数字

    快排流程参考

    int partition(vector<int> &num,int left,int right)
    {
        int index=left;
        int pivot=num[right];
        for(int i=left;i<right;i++){
            if (num[i]<pivot)
            {
                swap(num[i], num[index]);
                index++;
            }
        }
        swap(num[right], num[index]);
        return index;
    }
    void sort(vector<int> &num,int left,int right)
    {
        if(left>right)  return;
        int pindex = partition(num, left, right);
        sort(num, left, pindex - 1);
        sort(num, pindex + 1, right);
    }
    int sortk(vector<int> &num,int left,int right,int k)    //k smallest number
    {
        if(right==left)  return num[right];
        int index = partition(num, left, right);
        if(index-left+1==k) return num[k];
        else if(index-left+1>k)
            sortk(num, left, index - 1,k);
        else sortk(num, index + 1, right,k);
    }
    View Code

    33 折过的二分查找

    public class Solution {
        public int search(int[] nums, int target) {
            int start = 0;
            int end = nums.length - 1;
            while (start <= end){
                int mid = (start + end) / 2;
                if (nums[mid] == target)
                    return mid;
            
                if (nums[start] <= nums[mid]){
                     if (target < nums[mid] && target >= nums[start]) 
                        end = mid - 1;
                     else
                        start = mid + 1;
                } 
            
                if (nums[mid] <= nums[end]){
                    if (target > nums[mid] && target <= nums[end])
                        start = mid + 1;
                     else
                        end = mid - 1;
                }
            }
            return -1;
        }
    }
    View Code

    236 LCA

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root || root == p || root == q) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        return !left ? right : !right ? left : root;
    }
    View Code

    621 

    字典树

    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    #include<cstring>
    #include<cmath>
    #include<queue>
    #include<map>
    #include <sstream>
    using namespace std;
    #define MOD 1000000007
    const int INF=1000010;
    const double eps=1e-5;
    typedef long long ll;
    #define cl(a) memset(a,0,sizeof(a))
    #define ts printf("*****
    ");
    
    struct Trie
    {
        int ch[100][32];
        int sz=1;
        int val[100];
        Tire()
        {
            sz=1;
            memset(ch[0],0,sizeof(ch[0]));
        }
        void TireInsert(char *s,int v)
        {
            int u=0;
            int len=strlen(s);
            for(int i=0;i<len;i++){
                int c=s[i]-'a';
                if(!ch[u][c]){
                    memset(ch[sz],0,sizeof(ch[sz]));
                    val[sz]=0;
                    ch[u][c]=sz++;
                }
                u=ch[u][c];
            }
            val[u]=v;
        }
        void Tirecheck(char *s)
        {
            int u=0;
            int len=strlen(s);
            for(int i=0;i<len;i++){
                int c=s[i]-'a';
                if(!ch[u][c]){
                    printf("can not find such string
    ");
                    return;
                }
                u=ch[u][c];
            }
            string w="";
            dfs(u, s,w);
        }
        void dfs(int u,char *s,string w)
        {
            if(val[u]==1){
                cout<<s<<w<<endl;
            }
            for(int i=0;i<26;i++){
                if(ch[u][i]){
                    char k='a'+i;
                    string o=w+k;
                    dfs(ch[u][i],s,o);
                }
            }
        }
    };
    
    
    
    
    int main()
    {
        int a[10]={2,0,6,9,0,8,108};
        vector<int> nums;
        for(int i=0;i<7;i++){
            nums.push_back(a[i]);
        }
        char s1[20]="minaro";
        char s2[20]="mingugua";
        char s3[20]="ming";
        char s4[20]="min";
        char s5[20]="maxpro";
        char s6[20]="maxgugua";
        char s7[20]="maxg";
        char s8[20]="max";
    
        Trie t;
        t.TireInsert(s1,1);
        t.TireInsert(s2,1);
        t.TireInsert(s3,1);
        t.TireInsert(s4,1);
        t.TireInsert(s5,1);
        t.TireInsert(s6,1);
        t.TireInsert(s7,1);
        t.TireInsert(s8,1);
        cout<<t.sz<<endl;
        char ss1[20]="min";
        t.Tirecheck(ss1);
    
    }
    View Code

    146 LRU 链接

  • 相关阅读:
    Bzoj 3907: 网格
    [***]HZOJ 哪一天她能重回我身边
    HZOJ 那一天她离我而去
    HZOJ 那一天我们许下约定
    卡特兰数表
    组合数表
    [***]HZOJ 超级树
    HZOJ 砍树
    HZOJ 星际旅行
    「BZOJ2510」弱题
  • 原文地址:https://www.cnblogs.com/cnblogs321114287/p/7160746.html
Copyright © 2011-2022 走看看