LeetCode:Non-decreasing Array - 非减数列

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

转载于:https://my.oschina.net/Tsybius2014/blog/1542986

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值