C#LeetCode刷题之#665-非递减数列( Non-decreasing Array)

版权声明:Iori 的技术分享,所有内容均为本人原创,引用请注明出处,谢谢合作! https://blog.csdn.net/qq_31116753/article/details/82321484

问题

给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。

我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。

输入: [4,2,3]

输出: True

解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。

输入: [4,2,1]

输出: False

解释: 你不能在只改变一个元素的情况下将其变为非递减数列。

说明:  n 的范围为 [1, 10,000]。


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

Input: [4,2,3]

Output: True

Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

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


示例

public class Program {

    public static void Main(string[] args) {
        int[] nums = null;

        nums = new int[] { 4, 2, 3 };
        var res = CheckPossibility(nums);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static bool CheckPossibility(int[] nums) {
        //当发现逆序时,根据更后面1个值决定把当前值变成后面的
        //还是把后面的值变成前面的,最后判定数组是否升序即可
        for(int i = 0; i < nums.Length - 1; i++) {
            if(nums[i] > nums[i + 1]) {
                if(i + 2 < nums.Length && nums[i + 2] < nums[i]) {
                    nums[i] = nums[i + 1];
                } else {
                    nums[i + 1] = nums[i];
                }
                return IsSortedArray(nums);
            }
        }
        return true;
    }

    private static bool IsSortedArray(int[] nums) {
        //判断数组是否升序
        for(int i = 0; i < nums.Length - 1; i++) {
            if(nums[i] > nums[i + 1]) return false;
        }
        return true;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

True

分析:

显而易见,以上算法的时间复杂度为: O(n) 。

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/82321484