1. 程式人生 > >Leetcode_Array -- 665. Non-decreasing Array [easy]

Leetcode_Array -- 665. Non-decreasing Array [easy]

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).

給定一個由n個整陣列成的陣列,你的任務是判斷在最多修改陣列中一個元素的情況下,是否可以使這個陣列變成一個非降序排列的陣列

Example 1:

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.

Note: 1、The n belongs to [1, 10,000].

Solutions: 這道題的解題思路並不複雜,但需要考慮到所有情況。我們先用一個計數器記錄不滿足條件的個數,當個數大於2的時候直接返回False。觀察可知,只要不滿足情況都是當下元素大於其下一個元素,所以首先的判斷條件是:if nums[i]>nums[i+1],之後我們分情況將這個不符合的情況變成符合要求的情況(即用修補法進行修復)。如果再遇到不符合情況的時候就表明這個陣列無法一次轉換成功,直接返回False。可修改的情況分成三種,第一種:[4,2,3],即首元素不符合條件,這種可以變為True;第二種:[2,1,3,4],即陣列中i元素不符合條件,但i-1和i+1元素符合,這種也可以變為True;第三種:[2,3,1,2],陣列中i元素不符合,修改元素i後,其後元素仍然不符合條件。這三種情況對應了Python程式碼的三種判斷條件。

Python

(1)
class Solution:
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        count = 0
        for i in range(len(nums)-1):
            if nums[i]>nums[i+1]:
                count += 1
                if i == 0:
                    nums[i] = nums[i+1]
                elif nums[i+1]>nums[i-1]:
                    nums[i]= nums[i+1]
                else:
                    nums[i+1] = nums[i]
            if count > 1:
                return False
        return True

(2)
#方法2是將原陣列複製成兩份,只要遇到不符合條件的情況時,要麼修改i元素,要麼修改i+1元素
#修改之後直接將陣列排序,如果修改後的兩個陣列與排序後的陣列都不同,那麼直接返回False
#只要兩個陣列中有一個符合條件就返回True
class Solution(object):
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        one, two = nums[:], nums[:]
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                one[i] = nums[i + 1]
                two[i + 1] = nums[i]
                break
        return one == sorted(one) or two == sorted(two)
C++

class Solution {
public:
    bool checkPossibility(vector<int>& nums) {
        int count = 0;
        for (int i=0;i<nums.size()-1;i++){
            if (nums[i]>nums[i+1]){
                ++count;
                if (i == 0){
                    nums[i] = nums[i+1];
                }
                else if (nums[i+1]>nums[i-1]){
                    nums[i] = nums[i+1];
                }
                else{
                    nums[i+1] = nums[i];
                }
            }
            if (count>1){
                return false;
            }
        
        }
        return true;
    }
};