zoukankan      html  css  js  c++  java
  • leetcode 665

    665. Non-decreasing Array

    Input: [4,2,3]
    Output: True
    Explanation: You could modify the first 4 to 1 to get a non-decreasing array.递增

    思路:贪心思想,找异常值,存在两个以上则返回false。如果当前的值比前一的值小,并且也比前两的值小,此时只需更改当前值,而不更改前两个值。

    更改规则是用前一的值代替当前值。

    两种情况

    例如: 2   2   1  -》  2  2  2

                0   2   1  -》  0  1  1

    bool checkPossibility(vector<int>& nums) {
            int cnt = 0;                                                                    //如果存在两个以上的异常值则直接返回false
            for(int i = 1; i < nums.size() && cnt<=1 ; i++){
                if(nums[i-1] > nums[i]){                                                    //存在异常值
                    cnt++;
                    if(i-2<0 || nums[i-2] <= nums[i])nums[i-1] = nums[i];                    //i-2处理第一个边界值,这种||技巧经常用到
                    else nums[i] = nums[i-1];                                                //have to modify nums[i]
                }
            }
            return cnt<=1;
        } 

    669. Trim a Binary Search Tree

    Input: 
        3
       / 
      0   4
       
        2
       /
      1
    
      L = 1
      R = 3
    
    Output: 
          3
         / 
       2   
      /
     1
    
    The code works as recursion.
    
    If the root value in the range [L, R]
          we need return the root, but trim its left and right subtree;
    else if the root value < L
          because of binary search tree property, the root and the left subtree are not in range;
          we need return trimmed right subtree.
    else
          similarly we need return trimmed left subtree.
    
    Without freeing memory
    
    class Solution {
    public:
        TreeNode* trimBST(TreeNode* root, int L, int R) {
            if (root == NULL) return NULL;
            if (root->val < L) return trimBST(root->right, L, R);
            if (root->val > R) return trimBST(root->left, L, R);
            root->left = trimBST(root->left, L, R);
            root->right = trimBST(root->right, L, R);
            return root;
        }
    };

     总结:树的遍历bfs,一般结构:

     当前root

    ////////////////////////////

    中间逻辑,比如深一层的遍历

    ///////////////////////////

     对当前root进行操作,例如左右边子树的赋值操作

  • 相关阅读:
    网络七层
    微信小程序开发工具 常用快捷键
    BZOJ 1026 windy数 (数位DP)
    BZOJ 1026 windy数 (数位DP)
    CodeForces 55D Beautiful numbers (SPOJ JZPEXT 数位DP)
    CodeForces 55D Beautiful numbers (SPOJ JZPEXT 数位DP)
    HDU 3709 Balanced Number (数位DP)
    HDU 3709 Balanced Number (数位DP)
    UVA 11361 Investigating Div-Sum Property (数位DP)
    UVA 11361 Investigating Div-Sum Property (数位DP)
  • 原文地址:https://www.cnblogs.com/hotsnow/p/10075662.html
Copyright © 2011-2022 走看看