Test Development Preparation for Autumn Recruitment Interview 10-Heap/Stack/Queue of Niu Ke Brushing Questions

After working hard for so many years, looking back, it is almost all long setbacks and sufferings. For most people's life, smooth sailing is only occasional, and frustration, unbearable, anxiety and confusion are the main theme. We take the stage we did not choose, play the script we did not choose. Keep going!

Table of contents

1. Implement a queue with two stacks

2. The stack containing the min function

3. Valid parenthesis sequences

4. The maximum value of the sliding window

5. The smallest number of K

6. Find the Kth largest

7. The median in the data stream


1. Implement a queue with two stacks

Topic Link: Implementing Queues with Two Stacks

Idea: All elements are pushed into stack 1, then popped into stack 2, and finally popped from stack 2.

Java version:

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
       stack1.push(node) ;
    }
    
    public int pop() {
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.add(stack1.pop()) ;
            }
        }
        return stack2.pop() ;
      
    }
}

2. The stack containing the min function

Topic Link: Stack Containing Min Function_Niu Ke Topic_Niu Ke.

Idea: Use two stacks, one stack is used to maintain the push and pop, and the top element of the stack is taken, and the other stack is used to maintain the monotonic stack, which is also the top element of the stack.

Java Edition:

import java.util.Stack;

public class Solution {

    Stack<Integer> s1 = new Stack<>() ;
    Stack<Integer> s2 = new Stack<>() ;

    public void push(int node) {
        s1.push(node) ;
        if(s2.isEmpty() || s2.peek() > node){
            s2.push(node) ;
        }else{
            s2.push(s2.peek()) ;
        }
    }
    
    public void pop() {
        s1.pop() ;
        s2.pop() ;
    }
    
    public int top() {
       return  s1.peek() ;
    }
    
    public int min() {
        return s2.peek() ;
    }
}

3. Valid parenthesis sequences

Topic Link: Effective Bracket Sequence_Niuke题目霸_Niuke.com
Idea: Every time you encounter a left bracket, let the right bracket be pushed into the stack, and every time you encounter a right bracket, pop it out of the stack to match.

Java version:
 

import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    public boolean isValid (String s) {
        // write code here
        Stack<Character> s1 = new Stack<>() ;
        for(int i=0; i<s.length(); i++){
            if(s.charAt(i) == '{'){
                s1.add('}') ;
            }else if(s.charAt(i) == '('){
                s1.add(')') ;
            }else if(s.charAt(i) == '['){
                s1.add(']') ;
            }else if(s1.isEmpty() || s1.pop() != s.charAt(i)){
                return false ;
            }
        }
        return s1.isEmpty() ;
    }
}

4. The maximum value of the sliding window

Topic Link: Maximum Sliding Window

Idea: expose and enumerate all sliding windows, and compare the sizes of the values ​​in all windows in turn.
Violent version:

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size) {
        ArrayList<Integer> arrayList = new ArrayList<>() ;
        if(num.length == 0 || size > num.length || size == 0){
            return arrayList ;
        }
        for(int i=0; i<num.length-size+1; i++){
            int max = num[i] ;
            for(int j=i+1; j<i+size; j++){
                max = Math.max(max, num[j]) ;
            }
            arrayList.add(max) ;
        }
        return arrayList ;

    }
}

Idea 2: Maintain a double-ended monotonic queue, so that each time the queue is larger than the front, each new window requires the queue head element to be dequeued.

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size) {
        //利用双端队列,每次尾部进入保证比之前的小,每次下一个窗口时,移除头部元素
        ArrayList<Integer> arrayList = new ArrayList<Integer>() ;
        ArrayDeque<Integer> arrayDeque = new ArrayDeque<Integer>() ;
        if(size==0 || num.length == 0 || size > num.length){
            return arrayList ;
        }
        for(int i=0; i<size; i++){
            while(!arrayDeque.isEmpty() && num[arrayDeque.getLast()] < num[i]){
                arrayDeque.pollLast() ;
            }
            arrayDeque.addLast(i) ;
        }

        for(int i=size; i<num.length; i++){
            arrayList.add(num[arrayDeque.peekFirst()]) ;
            while(!arrayDeque.isEmpty() && num[arrayDeque.getLast()] < num[i]){
                arrayDeque.pollLast() ;
            }
            while(!arrayDeque.isEmpty() &&  (i-size+1) > arrayDeque.peekFirst()){
                arrayDeque.pollFirst() ;
            }
            arrayDeque.addLast(i) ;
        }
        arrayList.add(num[arrayDeque.peekFirst()]) ;
        return arrayList ;

    }
}

5. The smallest number of K

Topic link: The smallest number of K_Niuke Question Master_Niuke.com

Idea: direct sorting method.
Java version:

import java.util.*;

public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        //直接排序法
        ArrayList<Integer> arr = new ArrayList<>() ;
        Arrays.sort(input) ;
        for(int i=0; i<k; i++){
            arr.add(input[i]) ;
        }
        return arr ;
    }
}

Idea 2: Create a large root heap with a capacity of k, compare the top element of the heap every time, if the current element is smaller than the top element of the heap, replace it.

import java.util.*;

public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        //堆排序法,建立容量为k的优先队列构成的大根堆
       
        ArrayList<Integer> list = new ArrayList<>() ;
         if(input.length == 0 || k == 0){
            return list ;
         }
        PriorityQueue<Integer> queue = new PriorityQueue<>((o1,o2)->o2-o1) ;
        for(int i=0; i<input.length; i++){
            if(queue.size() < k){
                queue.add(input[i]) ;
            }else{
                if(input[i] < queue.peek()){
                    queue.poll() ;
                    queue.add(input[i]) ;
                }
            }
        }
        while(!queue.isEmpty()){
            list.add(queue.peek()) ;
            queue.poll() ;
        }
        return list ;
    }
}

6. Find the Kth largest

Topic Link: Finding the Kth Big_Niuke Topic_Niuke.com

Idea: Sort directly, and then return the Kth from the bottom.

Java version:

import java.util.*;

public class Solution {
    public int findKth(int[] a, int n, int K) {
        // write code here
        Arrays.sort(a) ;
        return a[n - K] ;
    }
}

7. The median in the data stream

Topic Link: Median in Data Streams

Idea: sort first, then take the median.

Java version:


import java.util.* ;

public class Solution {
    ArrayList<Integer> arrayList = new ArrayList<>() ;
    public void Insert(Integer num) {
        arrayList.add(num) ;
        Collections.sort(arrayList) ;
    }

    public Double GetMedian() {
        int n = arrayList.size() ;
        double result = (n%2==1)  ? (double)arrayList.get(n/2) : (double)(arrayList.get(n/2) + arrayList.get(n/2-1)) / 2 ;  
        return result ;
    }
}

Guess you like

Origin blog.csdn.net/nuist_NJUPT/article/details/130693258