leetcode 300. 最长上升子序列 354. 俄罗斯套娃信封问题

讲解:https://mp.weixin.qq.com/s/EWLi6sP3l4xsuc6GDpQAjw

https://mp.weixin.qq.com/s/wK3zCwMtT04DdvTo-FzQ1Q

 

https://leetcode-cn.com/problems/longest-increasing-subsequence/ (LIS)

 O(N^2)解法

class Solution {
public:
    int lengthOfLIS(vector& nums) {
        if (nums.size() == 0) return 0;
        
        vector dp(nums.size(), 1);
        int ans = 1;
        for (int i = 1; i < nums.size(); ++i)
        {
            for (int j = 0; j < i; ++j)
            {
                if (nums[j] < nums[i])                    
                    dp[i] = max(dp[i],dp[j]+1);
            }
            ans = max(dp[i],ans);
        }
        return ans;
    }
};

二分查找 O(NlogN)

class Solution {
public:
    int lengthOfLIS(vector& nums) {
        if (nums.size() == 0) return 0;
        
        int top[nums.size()]={};
        int piles = 0;
        
        for (int i = 0; i < nums.size(); ++i)
        {
            int poker = nums[i];
            int left = 0;
            int right = piles;
            while(left>1);
                if (top[mid] >= poker)
                {
                    right = mid;
                }
                else 
                {
                    left = mid + 1;
                }
            }
            
            if (left == piles) ++piles;
            top[left] = poker;
        }
        return piles;
    }
};

https://leetcode-cn.com/problems/russian-doll-envelopes/ (俄罗斯套娃)

bool cmp(const vector &a, const vector &b)
{
    if (a[0] == b[0])
        return a[1] > b[1];
    return a[0] < b[0];
}

class Solution {
public:
    int maxEnvelopes(vector>& envelopes) {
        sort(envelopes.begin(), envelopes.end(), cmp);
        vector height(envelopes.size());
        for (int i = 0; i < envelopes.size(); ++i)
            height[i] = envelopes[i][1];
        
        return lengthOfLIS(height);
    }
    
    int lengthOfLIS(vector& nums) {
        if (nums.size() == 0) return 0;
        
        int top[nums.size()]={};
        int piles = 0;
        
        for (int i = 0; i < nums.size(); ++i)
        {
            int poker = nums[i];
            int left = 0;
            int right = piles;
            while(left>1);
                if (top[mid] >= poker)
                {
                    right = mid;
                }
                else 
                {
                    left = mid + 1;
                }
            }
            
            if (left == piles) ++piles;
            top[left] = poker;
        }
        return piles;
    }    
};

 

你可能感兴趣的:(leetcode,面试算法)