1. 程式人生 > 其它 >力扣_設計問題

力扣_設計問題

打亂陣列

/**  * Your Solution object will be instantiated and called as such:  * Solution obj = new Solution(nums);  * int[] param_1 = obj.reset();  * int[] param_2 = obj.shuffle();  */  //設定一個數組shuffle為了儲存調換後的陣列,否則就返回不了以前的值  //設定一個隨機數為了保證哪種調換都是有可能的 class Solution {     int[] shuffle;     int[] nums;     Random random;
    public Solution(int[] nums) {         this.nums = nums;         random = new Random();     }     //用於重置為原來的資料     public int[] reset() {         return nums;     }     //用於返回重置後的資料     public int[] shuffle() {         shuffle = nums.clone();         for(int i = shuffle.length-1;i >= 0;i--){             int j = random.nextInt(i+1);
            swap(i,j);         }         return shuffle;     }     //交換資料     public void swap(int i,int j){         int temp = shuffle[i];         shuffle[i] = shuffle[j];         shuffle[j] = temp;     } }  

 

最小棧

/**  * Your MinStack object will be instantiated and called as such:  * MinStack obj = new MinStack();
 * obj.push(val);  * obj.pop();  * int param_3 = obj.top();  * int param_4 = obj.getMin();  */ //設定兩個棧,一個用來存不斷輸入的資料,一個用來存小的資料 class MinStack {         //設定兩個棧,一個用來存不斷輸入的資料,一個用來存小的資料     Deque<Integerstack;     Deque<IntegerminStack;     //初始化,建立兩個陣列,並且開始的時候將Integer的最大值存入暫時當做最大值     public MinStack() {         stack = new LinkedList<Integer>();         minStack = new LinkedList<Integer>();         minStack.push(Integer.MAX_VALUE);     }     //存入值,stack是存入隨時來的資料,minStack資料前需要判斷是否比它最小值要小才能存入     public void push(int val) {         stack.push(val);         minStack.push(Math.min(val,minStack.peek()));     }
    public void pop() {         stack.pop();         minStack.pop();     }          public int top() {         return stack.peek();     }          public int getMin() {         return minStack.peek();     } }