zoukankan      html  css  js  c++  java
  • 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     }

     

  • 相关阅读:
    普通的patch 和使用git 打patch
    c语言中的原子操作
    读写锁的简单说明
    source Insight 的常用设置
    git 一些常用的场景
    gdb 脚本 简单理解
    linux 中的errno 和 strerror(errno)
    C++中内存对齐原理详解
    如何安装windbg调试助手
    Windows中如何读写INI文件
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7672599.html
Copyright © 2011-2022 走看看