665. Non-decreasing Array

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).

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: The n belongs to [1, 10,000].

给定一个具有N个整型元素的数组,检查该数组是否能够通过最多改变一个元素的值,从而使得其本身变为单调非减数组,我们定义单调非减是指对于数组中的每一个有效下标i,都有 a[i] <= a[i+1]。 

 1     public boolean checkPossibility(int[] nums) {
 2         boolean changed = false;
 3         for (int i = 0; i < nums.length - 1; i++) {
 4             if (nums[i] > nums[i + 1]) {
 5                 if (!changed) {
 6                     if (i == 0 || nums[i-1] <= nums[i+1]) {
 7                         nums[i] = nums[i+1];
 8                     }else
 9                     {
10                         nums[i+1] = nums[i];
11                     }
12                     changed = true;
13                 } else {
14                     return false;
15                 }
16             }
17         }
18         return true;
19     }

 

 

posted @ 2017-10-15 16:31  daniel456  阅读(145)  评论(0编辑  收藏  举报