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).
题意:给定一个数组,只调整一个元素的条件下,该数组能否变成一个递增的数组,
思路:(参考)用贪心算法,当发现nums[i-1]>nums[i]时,我们希望通过改变一个值,使局部递增。
当没有nums[i-2],或者nums[i-2] <= nums[i]时,将nums[i-1]=nums[i],这样使得局部有序;
当nums[i-2]>nums[i]时,将nums[i-1]=nums[i],因为nums[i-1]>=nums[i-2],所以做修改后,局部有序;
修改完一次后,如果还有降序的元素,则该数组不符合条件。
1 class Solution { 2 public boolean checkPossibility(int[] nums) { 3 int cnt = 0,len = nums.length; ; 4 for(int i = 1; i < len && cnt<=1 ; i++){ 5 if(nums[i-1] > nums[i]){ 6 cnt++; 7 if(i-2<0 || nums[i-2] <= nums[i])nums[i-1] = nums[i]; 8 else nums[i] = nums[i-1]; 9 } 10 } 11 return cnt<=1; 12 } 13 }
原文地址:https://www.cnblogs.com/DongPingAn/p/9038449.html
时间: 2024-11-09 03:14:29