Return to school: Question 8-896. Monotonic sequence solution with three methods

896. Monotone Sequence

If the array is monotonically increasing or monotonically decreasing, then it is monotonic.

If for all i <= j, A[i] <= A[j], then the array A is monotonically increasing. If for all i <= j, A[i]> = A[j], then the array A is monotonically decreasing.

It returns true when the given array A is a monotonic array, otherwise it returns false.

示例 1:

输入:[1,2,2,3]
输出:true
示例 2:

输入:[6,5,4,4]
输出:true
示例 3:

输入:[1,3,2]
输出:false
示例 4:

输入:[1,2,4,5]
输出:true
示例 5:

输入:[1,1,1]
输出:true
 

提示:

1 <= A.length <= 50000
-100000 <= A[i] <= 100000

answer:

There are many methods for this problem, the easiest one to think of first is method one: two traversals.
That is, traverse the array once to see if it is incrementing, if it is, then exit, if not, then traverse it again to see if it is decrementing.

Method 2: Use judgment variables to achieve one traversal

That is, we first define a variable temp=0, and then start traversal, when the first traversal to A[i]-A[i-1] is not 0, use temp to store A[i]-A[i-1] Therefore, we can know from the positive or negative of temp whether we should judge from the increasing aspect or from the decreasing aspect.

Code:

bool isMonotonic(int* A, int ASize){
    
    
    if(ASize==1||ASize==2)
    {
    
    
        return 1;
    }
    int temp = 0;
    for(int i=1;i<ASize;i++)
    {
    
    
        if(A[i]==A[i-1])
        {
    
    
            continue;
        }
        if(temp==0)
        {
    
    
            temp = A[i]-A[i-1];
        }
        if(temp>0)
        {
    
    
            if(A[i]<A[i-1])
            {
    
    
                return 0;
            }
        }
        if(temp<0)
        {
    
    
            if(A[i]>A[i-1])
            {
    
    
                return 0;
            }
        }
    }
    return 1;
}

Method 3: Use the hash idea to achieve a traversal

We can consider this: if the sequence is an increasing sequence and there are n numbers, we need to compare n-1 times, then if there are sta times that are equal, and up times are in line with the increase, then we must There is up+sta==n-1, and the same is true for decreasing.
So use variable counting, just apply.

Code:

bool isMonotonic(int* A, int ASize){
    
    
    if(ASize==1||ASize==2)
    {
    
    
        return 1;
    }
    int up = 0;
    int down = 0;
    int sta = 0;
    for(int i=1;i<ASize;i++)
    {
    
    
        if(A[i]==A[i-1])
        {
    
    
            sta++;
        }
        if(A[i]>A[i-1])
        {
    
    
            up++;
        }
        if(A[i]<A[i-1])
        {
    
    
            down++;
        }
    }
    return (up+sta==ASize-1)||(down+sta==ASize-1)?1:0;
}

Guess you like

Origin blog.csdn.net/xiangguang_fight/article/details/114701029