LeetCode:Non-decreasing Array - 非减数列

原创
2017/09/25 17:03
阅读数 223

1、题目名称

Non-decreasing Array(非减数列)

2、题目地址

https://leetcode.com/problems/non-decreasing-array/description/

3、题目内容

英文:

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各整数构成的数组,你的目标是检查数组是否可在最多修改一个数字的情况下成为非减数组

4、解题方法

解决本题的要点在于找出一些规律:

1、当数组长度小于3时数组一定是合法的

2、存在波动模式3-5-1-2、3-5-1-3、3-5-1-4等的数组一定是不合法的

3、对于存在后一个数字比前一个数字小的数组,此类情况若出现两次以上就是不合法的

Java代码如下:

/**
 * LeetCode 665 - Non-decreasing Array 
 * @文件名称 Solution.java
 * @文件作者 Tsybius2014
 * @创建时间 2017年9月25日14:42:51
 */
class Solution {
	
	/**
	 * 检查数组是否可在最多修改一个数字的情况下成为非减数组
	 * @param nums 数列
	 * @return
	 */
    public boolean checkPossibility(int[] nums) {
        
        if (nums.length <= 2) {
            return true;
        }
        
        int count = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            //波动形式 3-5-1-2 3-5-1-3 3-5-1-4 等无解
            if (i < nums.length - 3) {
                if (nums[i] > nums[i + 2] && nums[i + 1] > nums[i + 2] && 
                    nums[i + 1] > nums[i + 3]) {
                    return false;
                }
            }
            //下滑趋势都记录为必须挪一次
            if (nums[i] > nums[i + 1]) {
                count++;
                if (count == 2) {
                    return false;
                }
                continue;
            }
        }
        
        return true;
    }
}

END

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部