力扣_设计问题
作者:互联网
打乱数组
/** * 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<Integer> stack; Deque<Integer> minStack; //初始化,创建两个数组,并且开始的时候将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(); } }
标签:问题,shuffle,minStack,nums,int,力扣,obj,设计,public 来源: https://www.cnblogs.com/Space-guan/p/15980250.html