< LeetCode > question brushing record

Posted by PHPcoder25 on Sat, 19 Feb 2022 03:02:38 +0100

Bracket sequence

import java.util.*;


public class Solution {
    /**
     * 
     * @param s string character string 
     * @return bool Boolean type
     */
    public boolean isValid (String s) {
        // write code here
        Stack<Character> stack=new Stack<>();
        for(char ch:s.toCharArray())    //Convert string to character array
        {
            if(ch=='(')
                stack.push(')');
            else if(ch=='[')
                stack.push(']');
            else if(ch=='{')
                stack.push('}');
                //If the stack is empty, the right statement will not be executed, so don't worry about empty stack pop
                //At this step, the description symbols are),],}, so if the stack is empty or there is no equivalent, the bracket will not match correctly
            else if(stack.empty() || stack.pop()!=ch)  
                return false;
        }
        
        return stack.empty();   //If the stack is empty, it returns true, which does not mean that it is normal to match after running. It may be ((()), which is a mismatch
    }
    

}

Queue with two stacks

import java.util.Stack;

public class Solution {
    //Take the top of stack 1 as the tail of the queue and the top of stack 2 as the head of the queue
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    
    //push normally
    public void push(int node) {
        stack1.push(node);
    }
    
    //During pop, all the elements of stack1 are transferred to stack2, so that the elements at the bottom of the original stack1 run to the top of stack2 stack, which realizes the function of queue first in first out
    //At the same time, pay attention to restore stack1 as it is. Here, stack2 is only used as a transit station, and the elements are really saved in stack1
    public int pop() {
        while(!stack1.empty())
        {
            stack2.push(stack1.pop());
        }
        int ans=stack2.pop();
        while(!stack2.empty())
        {
            stack1.push(stack2.pop());
        }
        
        return ans;
    
    }
}
  • Using Stack to do this problem will cause slow speed; The reason is that Stack inherits the Vector interface, and the underlying layer of Vector is an Object [] array, so the problem of space expansion and displacement should be considered. LinkedList can be used as the container of Stack. Because LinkedList implements the Deque interface, LinkedList can do everything that Stack can do. Its structure is a two-way linked list with less expansion consumption.
class CQueue {

    LinkedList<Integer> stack1;
    LinkedList<Integer> stack2;
    public CQueue() {
        stack1=new LinkedList<Integer>();
        stack2=new LinkedList<Integer>();
    }
    
    public void appendTail(int value) {
        stack1.add(value);
    }
    
    public int deleteHead() {
        while(!stack1.isEmpty())
        {
            stack2.add(stack1.pop());
        }
        int ans=-1;
        if(!stack2.isEmpty())
            {
                ans=stack2.pop();              
            }


        return ans;
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

Binary search idea:
1. First, determine the subscript in the middle of the array
mid=(left+right)/2;
2. Then compare the number findVal to arr[mid]
① If findval > arr [mid], it means that the number to be searched is on the right of mid, so it needs to be searched recursively to the right
② If findval < arr [mid], it means that the number to be searched is to the left of mid, so it needs to be searched to the left recursively
③ findVal==arr[mid], indicating that if it is found, it returns

End recursion condition:
1. End if found
2. Recursion complete array, findVal still not found, end recursion. That is, left > right.

Binary search (including duplicate numbers, return to the first occurrence position)

First, carry out the step of binary search normally, and then deal with the first position when returning to the main program.

  • When the return value is less than or equal to 0, no processing is required
  • Otherwise, keep judging the number on the left to see whether it is equal to target until an unequal number is found in the valid position. Remember to add one when returning
import java.util.*;


public class Solution {
    /**
     * The class name, method name and parameter name in the code have been specified. Do not modify them. Just return the value specified by the method directly
     *
     * Returns a subscript if the target value exists, otherwise returns - 1
     * @param nums int Integer one-dimensional array 
     * @param target int integer 
     * @return int integer
     */
    public int search (int[] nums, int target) {
        // write code here
        int position=binarySearch(nums,0,nums.length-1,target);
        if(position<=0)
            return position;
        else
        {
            int tmp=position;
            while(--tmp>=0 && nums[tmp]==target)
            {
               continue;
            }
            position=tmp+1;
            
        }
        return position;
    }
    
    public static int binarySearch(int arr[],int left,int right,int target)
    {
        if(left>right)
            return -1;
        
        int mid=(left+right)/2;
        
        if(target==arr[mid])
            return mid;
        if(target<arr[mid])
            return binarySearch(arr,left,mid-1,target);
        else
            return binarySearch(arr,mid+1,right,target);

    }
}

The entry node of the link in the linked list
meaning of the title
Give a linked list. If it contains a ring, please find the entry node of the ring of the linked list. Otherwise, null will be output.

Problem solving ideas
The entry node is the first node to arrive again in the traversal process.

Step 1: make sure that the linked list contains links
Method: two pointers start from the node at the same time, one step at a time and two steps at a time. If the fast pointer catches up with the slow one, it means there is a ring. If the fast pointer goes to the end of the linked list, it means there is no ring.
Step 2: find the number of nodes in the ring
Method: because the node where the above two nodes meet must be in the ring, start from this node and go to this node again to calculate the number of nodes in the ring.
Step 3: find the entry node of the link in the linked list
Method: two pointers start from the chain header node. One first takes several steps of the ring node, and then the two pointers move forward at the same time. The node where the two pointers meet is the entry node of the ring.

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {

        
        //First judge whether there is a ring
        if(isCircle(head)==false)
            return null;
        else
        {
            //If there is a ring, judge the number of nodes of the ring
            ListNode meetNode=getMeetNode(head);
            ListNode fast=meetNode;
            ListNode slow=meetNode;
            int count=1;  //Number of nodes to save the ring
            while(fast.next!=slow)
            {
                fast=fast.next;
                count++;
            }
            
            //After the number of nodes of the ring has been obtained
            //Point two pointers to the first node, and then let a node go through the ring first. The number of nodes n
            
            fast=head;
            slow=head;
            while(count-->0)
            {
                fast=fast.next;
            }
            while(fast!=slow)
            {
                fast=fast.next;
                slow=slow.next;
                    
            }
            
            return fast;
            
        }
            
        
        
    }
    
    public boolean isCircle(ListNode head)
    {
        ListNode tmp=head;
        ListNode fast=tmp;
        ListNode slow=tmp;
        while(fast!=null && fast.next!=null)
        {
            fast=fast.next.next;
            slow=slow.next;
            
            if(slow==fast)
            {
                return true;
            }
              
        }
        return false;
        
    }
    
    public ListNode getMeetNode(ListNode head)
    {
        ListNode tmp=head;
        ListNode fast=tmp;
        ListNode slow=tmp;
        
        
        while(true)
        {  fast=fast.next.next;
            slow=slow.next;

            if(slow==fast)
            {
                return fast;
            }
        }     
        
  
    }
}

Binary tree depth
Recursive implementation
If the end condition is that the current node is empty, 0 will be returned
Otherwise, it recurses to the left and right subtrees.
Each recursion returns the maximum value of both + 1

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)
            return 0;

 
        int    leftLen=maxDepth(root.left);
        int    rightLen=maxDepth(root.right);

        return 1+Math.max(leftLen,rightLen);
    }
}

Binary tree sequence traversal and output results
Answer reference

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        //List<List<Integer>> res=new ArrayList<ArrayList<Integer>>();  
        //This definition is wrong
        List<List<Integer>> res=new ArrayList<>();  
        //be careful!! It's Deque
        Queue<TreeNode> queue=new ArrayDeque<>();
        if(root==null)
            return res;
            //return queue;

        queue.add(root);
        //List<List<Integer>> res=new ArrayList<ArrayList<Integer>>();  
        //res cannot be defined here because list < list < integer > > is returned instead of queue
        while(!queue.isEmpty())
        {
            int n=queue.size();
            List<Integer> list=new ArrayList<>();
            for(int i=0;i<n;i++)
            {
                TreeNode node=queue.poll();
                list.add(node.val);
            
                if(node.left!=null)
                {
                    //Not root, queue Poll gets node
                    //queue.add(root.left);
                    queue.add(node.left);
                }
                if(node.right!=null)
                {
                    //queue.add(root.right);
                    queue.add(node.right);
                }

            }
            
                res.add(list);
        }
        
        return res;
    }
}

Left turn string
Important: the substring function to get the string is
substring(int begin,int end); (left closed right open)

String str=new String("HelloWorld");
String sub=str.substring(0,5);  //sub="Hello"

class Solution {
    public String reverseLeftWords(String s, int n) {
        String sub1=s.substring(0,n);
        String sub2=s.substring(n,s.length());

        return sub2+sub1;
    }
}

import java.util.*;


public class Solution {
    /**
     * The class name, method name and parameter name in the code have been specified. Do not modify them. Just return the value specified by the method directly
     *
     * 
     * @param s string character string 
     * @return string character string
     */
    public String replaceSpace (String s) {
        // write code here
        StringBuffer sb=new StringBuffer();
        char chArr[]=s.toCharArray();
        for(int i=0;i<s.length();i++)
        {
            if(chArr[i]!=' ')
            {
                sb.append(chArr[i]);
            }
            else
            {
                sb.append("%20");
            }
        }
        
        return sb.toString();
    }
}

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head==null || head.next==null)
            return head;
        //Traverse until the last node, and change the pointing relationship of adjacent nodes in the process of recursive return
        //Node is the last header node to return
        ListNode node=ReverseList(head.next);
        //Change the direction relationship
        head.next.next=head;
        head.next=null;
        
        return node;
    }
}

Longest non repeating substring

import java.util.*;


public class Solution {
    /**
     * 
     * @param arr int Integer one-dimensional array
     * @return int integer
     */
    /*
    Idea: first record the length of the substring that has been counted until there is a duplicate string, then delete all the elements from the head to here,
    Count again, and the final result is the largest return result res
    */
    public int maxLength (int[] arr) {
        // write code here
        if(arr.length<=1)
            return arr.length;
        
        int res=0;
        
        ArrayList<Integer> list=new ArrayList<>();
        list.add(arr[0]);
        for(int i=1;i<arr.length;i++)
        {
            if(list.contains(arr[i]))
            {
                int p=list.indexOf(arr[i]);
                while(p>=0)
                {
                    list.remove(0);
                    p--;
                }
            }

            list.add(arr[i]);
            
            res=Math.max(list.size(),res);
        }
        
        return res;
        
        
    }
}

Fibonacci sequence

Recursion:

public class Solution {
    public int Fibonacci(int n) {
        if(n<=1)
            return n;
        return Fibonacci(n-1)+Fibonacci(n-2);
    }
}

Using arrays:

public class Solution {
    public int Fibonacci(int n) {
        if(n<=1)
            return n;
        
        int arr[]=new int[40];
        arr[0]=0;
        arr[1]=1;
        int i;
        for(i=2;i<=n;i++)
        {
            arr[i]=arr[i-1]+arr[i-2];
        }
        return arr[n];
    }
}

Without array:

public class Solution {
    public int Fibonacci(int n) {
        if(n<=1)
            return n;
        
        int i=2;
        int value1=0,value2=1,res=0;
        while(i++<=n)
        {
            res=value1+value2;
            value1=value2;
            value2=res;
        }
        return res;
    }
}

Minimum number of k

Because only the smallest k numbers are selected, there is no need to sort completely. You can use selective sorting. You can exit the cycle as long as k are selected

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> list=new ArrayList<>();
        
        if(input.length<k)
            return list;
        
        int count=0;
        int i=0;
        int position=0;
        while(count<k && i<input.length)
        {
            //Using selective sorting, find the smallest one at a time

            int minNum=input[position],minPosition=position;
            int j;
            for(j=position;j<input.length;j++)
            {
               if(minNum>input[j])
               {
                   minNum=input[j];
                   minPosition=j;
               }
            }
            

            input[minPosition]=input[position];
            //input[position]=minNum;
            
            list.add(minNum);
            count++;
            position++;
        }
        
        return list;
    }
}

Merge two ordered arrays

Traverse from back to front, and insert the larger number first
Since the number of B is inserted into A, there is no need to do anything if the array A has surplus after traversal. If the array B has surplus, the elements in the array B need to be moved to A

public class Solution {
    public void merge(int A[], int m, int B[], int n) {
        int i=m-1,j=n-1;
        int p=A.length-1;
        while(i>=0 && j>=0)
        {
            if(A[i]<B[j])
            {
                A[p--]=B[j--];
            }
            else
            {
                A[p--]=A[i--];
            }
        }
        while(j>=0)
        {
            A[p--]=B[j--];
        }
    }
}

Sword finger Offer 52 The first common node of two linked lists

Idea: the lengths of the two linked lists are L1+C and L2+C respectively, and C is the length of the public part. Method: after the first person takes step L1+C, return to the starting point of the second person and take step L2; After returning to the starting point of L1 + 2, step 1. When the steps taken by two people are L1+L2+C, the two guys fall in love

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode node1=headA;
        ListNode node2=headB;

        while(node1!=node2)
        {
            node1=node1==null?headB:node1.next;
            node2=node2==null?headA:node2.next;
        }

        return node1;
    }
}

Topics: Java