1. 程式人生 > >貪心演算法LeetCode 665 Non-decreasing Array

貪心演算法LeetCode 665 Non-decreasing Array

LeetCode 665

Non-decreasing Array

  • Example:
    (1)[2, 3, 3, 2, 4]——true
    (2)[-1, 4, 2, 3]——true
    (3)[3, 4, 2, 3]——false
  • Solution:
    • 解題思路:根據樣例才推出判斷條件的TAT
    • 程式設計實現:
class Solution {
public:
    bool checkPossibility(vector<int>& nums) {
        if (nums.size() == 0||nums.size() == 1) return true
; int count = 0; for (int i = 0; i <= nums.size()-2; i++) { if (nums[i]>nums[i+1]) { if (count == 0) { if (i >= 1 && i <= nums.size()-3) { if (nums[i-1]>nums[i+1]&&nums[i]>nums[i+2]) return
false; } } else { return false; } count++; } } return true; } };