Record brushing questions-(leetcode-665 non-decreasing sequence)

Topic: Give you an integer array of length n. Please judge whether the array can become a non-decreasing sequence when at most one element is changed.
We define a non-decreasing sequence like this: For all i (1 <= i <n) in the array, array[i] <= array[i + 1] is always satisfied.
Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/non-decreasing-array
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Idea: After encountering the former is greater than, reduce the former while saving the subscript and value of the former and exit the loop, and start from the beginning; after encountering the former greater than again, use the previously saved value to enlarge the latter value and the first in the first comparison The former in the second comparison is consistent and exits the loop, and then starts the comparison again from the beginning, and exits the loop when the previous is greater than the back and outputs false.
Code:

bool checkPossibility(int* nums, int numsSize){
    
    
    int temp=0,flag=0;
    for(int i=0;i<numsSize-1;i++){
    
    
        if(nums[i]>nums[i+1]){
    
    
            temp = nums[i];
            nums[i]=nums[i+1];
            flag = i;
            break;
        }
    }
    for(int i=0;i<numsSize-1;i++){
    
    
        if(nums[i]>nums[i+1]){
    
    
            nums[flag] = nums[flag+1] = temp;
            break;
        }
    }
    for(int i=0;i<numsSize-1;i++){
    
    
        if(nums[i]>nums[i+1])
            return false;
    }
    return true;
}

Guess you like

Origin blog.csdn.net/lthahaha/article/details/106254318