leetcode 题集

775. Global and Local Inversions

统计相邻元素组成的逆序对(local inversion)和全局逆序对的数量(global inversion)

思路:local inversion 很容易扫一遍即可,global逆序对可以用树状数组进行统计.

class Solution {
public:
    int C[5005];
    int lowbit(int x){
        return x&(-x);
    }
    void Insert(int id,int v){
        for(int i=id;i<5005;i+=lowbit(i)){
            C[i]+=v;
        }
    }
    int getsum(int id){
        int sum = 0;
        for(int i=id;i>0;i-=lowbit(i)){
            sum+=C[i];
        }
        return sum;
    }
    bool isIdealPermutation(vector<int>& A) {
        if(A.size()==1) return true;
        int local = 0,global = 0;
        memset(C,0,sizeof(C));
        for(int i=0;i<A.size();i++){
            if(i<A.size()-1&&A[i]>A[i+1]) local++;
            Insert(A[i]+1,1);
            global+=(i+1-getsum(A[i]+1));
        }
        return local==global;
    }
};
View Code

674. Longest Continuous Increasing Subsequence

最长连续上升子序列

if a[i]>a[i-1]: dp[i] = dp[i-1]+1 else: dp[i] = 1

class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        if(nums.size()==0) return 0;
        int dp[10005];
        dp[0] = 1;
        int mx = 1;
        for(int i=1;i<nums.size();i++){
            if(nums[i]>nums[i-1]) dp[i] = dp[i-1]+1;
            else dp[i] = 1;
            mx = max(mx,dp[i]);
        }
        return mx;
    }
};
View Code

 

posted @ 2018-02-08 22:47  樱花庄的龙之介大人  阅读(...)  评论(... 编辑 收藏