1. 程式人生 > >LeetCode Weekly Contest 111 941&942&944

LeetCode Weekly Contest 111 941&942&944

941

思路:找到最高點,最高點只能有一個,且不能是左右端點,從最高點往左右判斷,如果有不是單調遞減的就直接return false,

class Solution {
public:
    bool validMountainArray(vector<int>& A) {
        int len = A.size();
        int maxx = -9999999; int count = 0;
        int pos = -1;
        if(len<3) return false;
        else{
            
            for(int i = 0; i < len; i++){ 
                
                if(A[i]>maxx){
                    maxx = A[i]; count = 1; pos = i;
                }else if(A[i]==maxx){
                    count++;
                }
                
            }
            if(count==1){
                if(pos>0 && pos<len-1 ) {
                    
                    for(int i = pos; i>0; i--){
                        if(A[i]<=A[i-1]) return false;
                    }
                    for(int i = pos; i <len-1; i++){
                        if(A[i+1]>=A[i]) return false;
                    }
                    return true;
                }
            }
            return false;
        }
    }
};

942

因為數不能相同,所以就把為I的從1開始一次加一,把為D的從-1開始一次減一,原始陣列初始化為0,最後把負的變成正的,就是符合題意的解,整體加上最小的那個負數-1.

class Solution {
public:
    vector<int> diStringMatch(string S) {
        vector<int> tmp;
        int len = S.length();
        int fu=1,zh=1;
        tmp.push_back(0);
        for(int i = 0; i < len; i++)
        {
            
            if(S[i]=='I'){
                tmp.push_back(zh);
                zh++;
            }else{
                tmp.push_back(0-fu);
                fu++;
            }
            
        }
        
        for(int i = 0; i < len+1; i++){
            tmp[i]=tmp[i]+fu-1; cout<<tmp[i]<<" ";
        }
        
        return tmp;
    }
};

944

不明白這個為什麼是medium,明明比上道題簡單,(還是我想複雜了),這個直接二重迴圈就完了,不符合題意的直接+1

class Solution {
public:
    int minDeletionSize(vector<string>& A) {
        int len = A.size(); int llen = A[0].length();
        int ans = 0;
      cout<<len<<endl<<llen<<endl;
            for(int j = 0; j < llen; j++){
                for(int i = 0; i < len-1; i++){ 
                
                 if(A[i][j]>A[i+1][j])  {
                    ans++;
                     cout<<i<<" "<<j<<endl;
                     break;   
                 }
                
            }    
        }
        
        return ans;
    }
};