码迷,mamicode.com
首页 > 其他好文 > 详细

665. Non-decreasing Array

时间:2017-10-15 17:35:53      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:else   input   change   数组   asi   元素   integer   ssi   blog   

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     }

 

 

665. Non-decreasing Array

标签:else   input   change   数组   asi   元素   integer   ssi   blog   

原文地址:http://www.cnblogs.com/wzj4858/p/7672599.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!