115 - 665 非递减数列
Last updated
Was this helpful?
Last updated
Was this helpful?
给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。
我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。
示例 1:
输入: [4,2,3] 输出: True 解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。
示例 2:
输入: [4,2,1] 输出: False 解释: 你不能在只改变一个元素的情况下将其变为非递减数列。
说明: n 的范围为 [1, 10,000]。
感觉就是单纯搞脑子的题。。。
三个以内,怎样排都行
三个以上,假设有三个数x/y/z。如果x>z,就让z=y;如果x<z,就让y=z
如果三个以上变更超过两次,就不行
Runtime: 76 ms, faster than 20.89% of JavaScript online submissions for Non-decreasing Array.
Memory Usage: 36.8 MB, less than 100.00% of JavaScript online submissions for Non-decreasing Array.
Runtime: 224 ms, faster than 51.37% of Python3 online submissions for Non-decreasing Array.
Memory Usage: 15.1 MB, less than 6.67% of Python3 online submissions for Non-decreasing Array.
Runtime: 24 ms, faster than 85.19% of Go online submissions for Non-decreasing Array.
Memory Usage: 6.2 MB, less than 100.00% of Go online submissions for Non-decreasing Array.
这种做法的思路一样,但实现起来更加快
Runtime: 64 ms, faster than 79.50% of JavaScript online submissions for Non-decreasing Array.
Memory Usage: 36.6 MB, less than 100.00% of JavaScript online submissions for Non-decreasing Array.
可能是因为,上一种做法每次for循环都要判断导致降低了速度
毕竟中招是小概率事件,每次判断有点不值得。最好是最后一起判断
Runtime: 24 ms, faster than 85.07% of Go online submissions for Non-decreasing Array.
Memory Usage: 6.2 MB, less than 100.00% of Go online submissions for Non-decreasing Array.
Runtime: 264 ms, faster than 8.52% of Python3 online submissions for Non-decreasing Array.
Memory Usage: 15.1 MB, less than 6.67% of Python3 online submissions for Non-decreasing Array.