Trivial C solution.

  • 0

    After we found the decreasing pair of numbers, which one should we modify?
    It's easier to duplicate the array, (so we have 2 arrays)
    and one of them assign n-th number to the n+1-th one,
    the other do the reverse.

    Then check the sequence again to tell the result.

    bool checkPossibility(int* nums, int numsSize) {
        int i = 0 ;
        bool result = true;
        bool result1 = true;
        if (numsSize<=2)
            return true;
        int *nums1 = malloc(sizeof(int)*numsSize);
        if (!nums1)
            return false;
        memcpy (nums1, nums, sizeof(int)*numsSize);
        for (i=0; i < numsSize-1; i++)
            if (nums[i] > nums[i+1])
                nums[i+1] = nums[i];
                nums1[i] = nums1[i+1];
        for (i=0; i < numsSize-1; i++)
            if (nums[i] > nums[i+1])
                result = false;
            if (nums1[i] > nums1[i+1])
                result1 = false;
        if (nums1)
        return (result || result1);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.