leetcode 題集

775. Global and Local Inversions

統計相鄰元素組成的逆序對(local inversion)和全局逆序對的數量(global inversion)數組

思路:local inversion 很容易掃一遍便可,global逆序對能夠用樹狀數組進行統計.ide

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

最長連續上升子序列spa

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

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
相關文章
相關標籤/搜索