Weekly leetcode - 235/236/53/NC102/NC103

Keywords: jenkins ssh server

leetcode - 235. Nearest common ancestor of binary search tree

Given a binary search tree, find the nearest common ancestor of two specified nodes in the tree.

Baidu Encyclopedia defines the nearest public ancestor as: "for two nodes p and q with root tree T, the nearest public ancestor is expressed as a node x, which satisfies that x is the ancestor of p and q, and the depth of X is as large as possible (a node can also be its own ancestor)."

If node p is in the left (right) subtree of node root, or p = root, root is said to be the ancestor of p


The characteristic of binary search tree is that all nodes of the left subtree are smaller than the current node, and all nodes of the right subtree are larger than the current node, and each subtree has the above characteristics.

Problem solving ideas:

  1. If the values of both nodes are less than the root node, it means that they are both on the left subtree of the root node. Let's look on the left subtree
  2. If the values of both nodes are greater than the root node, it means that they are both on the right subtree of the root node. Let's look on the right subtree
  3. If a node value is greater than the root node and a node value is less than the root node, it means that they are on the left subtree of the root node and on the right subtree of the root node, then the root node is their nearest common ancestor node.


Method 1: iteration

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // If the difference between the root node and p,q is multiplied by a positive number, it means that the two differences are either positive or negative, that is, they must be on the same side of the root node, so continue to look down
        while ((root.val-p.val)*(root.val-q.val)>0){
           root =  root.val > p.val ? root.left : root.right;
        }
        // If the result of multiplication is negative, p and q are on both sides of the root node
        // If it is equal to 0, at least one is the root node, and the root node is returned directly
        return root;
    }
}

Method 2: recursion

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // For the exit of recursion, p and q are on both sides of the node, or one of p and q is the root node
        if((p.val-root.val)*(q.val-root.val)<=0){
            return root;
        }
        return lowestCommonAncestor(p.val>root.val?root.right:root.left,p,q);
    }
}

leetcode - 236. Nearest common ancestor of binary tree

Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.

Baidu Encyclopedia defines the nearest public ancestor as: "for two nodes p and q with root tree T, the nearest public ancestor is expressed as a node x, which satisfies that x is the ancestor of p and q, and the depth of X is as large as possible (a node can also be its own ancestor)."

Method 1: iterative method

/**
 * Iteration: sequence traversal, storing each node and the parent node of each node in the map, where the built node is node and the value is parentNode;
 */
class Solution {
      public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
           // Use HashMap to record each node and the parent node of each node
           HashMap<TreeNode, TreeNode> map = new HashMap<>();
           Queue<TreeNode> queue = new LinkedList<TreeNode>();
           // First put the root node into the map, and the parent node of the root node is null
           map.put(root,null);
           queue.add(root);
           // Traverse each node and store each node and its parent node in the map
           while (!queue.isEmpty()){
               TreeNode node = queue.poll();
               if(node.left!=null){
                   map.put(node.left,node);
                   queue.add(node.left);
               }
               if(node.right!=null){
                   map.put(node.right,node);
                   queue.add(node.right);
               }
           }
          HashSet<TreeNode> set = new HashSet<>();
           // Get the node path of the p node: the path from the root node to the p node
           while (p!=null){
               set.add(p);
               p = map.get(p);
           }

           // Check whether p and its ancestor nodes contain q nodes. If not, check whether they contain q parent nodes
            while (!set.contains(q)){
                q=map.get(q);
            }
            return q;
      }
}

Method 2: recursive method

/**
 * Iteration: sequence traversal, storing each node and the parent node of each node in the map, where the built node is node and the value is parentNode;
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null){
            return root;
        }
        // Find p and return directly
        if(root==p){
            return p;
        }
        // Find p and return directly
        if(root==q){
            return q;
        }
        TreeNode left = lowestCommonAncestor(root.left,p,q);  
        TreeNode right = lowestCommonAncestor(root.right,p,q);
        // It means that p and q may be on the right subtree. Anyway, the left subtree is not found, so left=null, so you need to find it in the right subtree
        if(left==null){
            return right;
        }
        if(right==null){
            return left;
        }
        // Note both left and right are not null, that is, they are located on both sides of root. Root is the common ancestor
        return root;
    }
}

Given an integer array nums, find a continuous sub array with the largest sum (the sub array contains at least one element) and return its maximum sum.

leetcode - 53. Maximum suborder sum

Given an integer array nums, find a continuous sub array with the largest sum (the sub array contains at least one element) and return its maximum sum.

Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
 Explanation: continuous subarray [4,-1,2,1] The sum of is 6.

Example 2:
Input: nums = [1]
Output: 1

Example 3:
Input: nums = [0]
Output: 0

Example 4:
Input: nums = [-1]
Output:-1

Example 5:
Input: nums = [-100000]
Output:-100000  

Problem solving ideas:

Method 1:

class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length==0 || nums==null){
            return 0;
        }
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int res = nums[0];
        for(int i=1;i<nums.length;i++){
            // Note that the number num [i] must be added to the continuous subarray. We need to consider whether to dp[i-1]
            if(dp[i-1]<0){
                // Discard dp[i-1], because without dp[i-1], nums[i] is larger
                dp[i] = nums[i];
            }else{
                // Add dp[i-1], because the sum of children is larger after adding dp[i-1]
                dp[i] = dp[i-1]+nums[i];
            }
            res = Math.max(res,dp[i]);
        }
        return res;
    }
}

Or write it more succinctly:

class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length==0 || nums==null){
            return 0;
        }
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int res = nums[0];
        for(int i=1;i<nums.length;i++){
            dp[i] = Math.max(dp[i-1]+nums[i],nums[i]);
            res = Math.max(res,dp[i]);
        }
        return res;
    }
}

Sword finger offer- NC102 finds the nearest common ancestor of two nodes in the binary tree

Given a binary tree (guaranteed to be non empty) and the val values o1 and o2 corresponding to the two nodes on the tree, please find the nearest common ancestor node of o1 and o2.

Requirements: space complexity O(1), time complexity O(n)

public class Solution {
    /**
     *
     * @param root TreeNode class
     * @param o1 int integer
     * @param o2 int integer
     * @return int integer
     */
    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        // write code here
        if(root==null) {
            return -1;
        }
        if(o1==root.val || o2==root.val) {
            return root.val;
        }
        int left = lowestCommonAncestor(root.left, o1, o2);
        int right = lowestCommonAncestor(root.right,o1,o2);
        if(left ==-1) {
            return right;
        }
        if(right ==-1) {
            return left;
        }
        return root.val;
    }
}

Sword finger offer - reverse string

Write a program, accept a string, and then output the inverted string. (string length no more than 1000)
Requirements: space complexity O(n), time complexity O(n)

public class Solution {
    /**
     * Reverse string
     * @param str string character string
     * @return string character string
     */
    public String solve (String str) {
        // write code here
        StringBuilder stringBuilder = new StringBuilder();
        for(int i=str.length()-1;i>=0;i--){
            stringBuilder.append(str.charAt(i));
        }
        return stringBuilder.toString();
    }
}

Posted by peeter_talvistu on Sat, 20 Nov 2021 20:16:00 -0800