【LeetCode】初级算法案例+java代码(设计问题篇)

174 阅读1分钟

文章目录


一、打乱数组

在这里插入图片描述

class Solution {

    int[] nums;
    // 用以打乱的数组
    int[] tempArr;

    public Solution(int[] nums) {
        this.nums = nums.clone();
        tempArr = nums.clone();
    }

    public int[] reset() {
        return nums;
    }
	
	// 随机两两互换进行打乱
    public int[] shuffle() {
        int r1 = new Random().nextInt(nums.length);
        int r2 = new Random().nextInt(nums.length);
        int temp = tempArr[r1];
        tempArr[r1] = tempArr[r2];
        tempArr[r2] = temp;
        return tempArr;
    }
    
}

二、最小栈

在这里插入图片描述

class MinStack {

    //链表头,相当于栈顶
    private ListNode head;

    //压栈,需要判断栈是否为空
    public void push(int x) {
        if (empty()) {
            head = new ListNode(x, x, null);
        } else {
            head = new ListNode(x, Math.min(x, head.min), head);
        }
    }

    //出栈,相当于把链表头删除
    public void pop() {
        if (empty()) {
            throw new IllegalStateException("Stack is Empty");
        }
        head = head.next;
    }

    //栈顶的值也就是链表头的值
    public int top() {
        if (empty()) {
            throw new IllegalStateException("Stack is Empty");
        }
        return head.val;
    }

    //链表中头结点保存的是整个链表最小的值,所以返回head.min也就是
    //相当于返回栈中最小的值
    public int getMin() {
        if (empty()) {
            throw new IllegalStateException("Stack is Empty");
        }
        return head.min;
    }

    //判断栈是否为空
    private boolean empty() {
        return head == null;
    }
}

class ListNode {
    public int val;
    public int min;//最小值
    public ListNode next;

    public ListNode(int val, int min, ListNode next) {
        this.val = val;
        this.min = min;
        this.next = next;
    }

}