Given an array
nums
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
nums[i] <= nums
[i + 1]
holds for every i
(0-based) such that (0 <= i <= n - 2)
.Example 1:
Input: nums ={4,2,3} Output: true
Approach
Java
public class NonDecreasingArray {public static void main(String[] args) {int[] nums = { 4, 2, 3 };System.out.println(checkPossibility(nums));}static boolean checkPossibility(int[] nums) {int n = nums.length, cnt = 0;for (int i = 0; i < n - 1 && cnt <= 1; i++) {if (nums[i] > nums[i + 1]) {if (i > 0) {if (nums[i - 1] <= nums[i + 1])nums[i] = nums[i - 1];elsenums[i + 1] = nums[i];}++cnt;}}return cnt <= 1;}}
C++
#include <bits/stdc++.h>using namespace std;bool checkPossibility(vector<int>& nums){int n=nums.size(),cnt=0;for (int i = 0; i <n-1 && cnt<=1;i++){if (nums[i] > nums[i + 1]){if (i > 0){if (nums[i - 1] <= nums[i + 1])nums[i] = nums[i - 1];elsenums[i + 1] = nums[i];}++cnt;}}return cnt<=1;}int main(){vector<int> nums ={4,2,3};if(checkPossibility(nums))cout<<"true";elsecout<<"false";return 0;}
No comments:
Post a Comment