设计问题
1.Shuffle an Array
打乱一个没有重复元素的数组。
示例:
// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();
// 重设数组到它的初始状态[1,2,3]。
solution.reset();
// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();
langage Java
class Solution {
int[] nums;
public Solution(int[] nums) {
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
}
}
/**
* 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();
*/
思路
从最后一个元素开始,将其与前面的随机元素交换
解法
java 解法
class Solution {
int[] nums;
public Solution(int[] nums) {
this.nums = nums;
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
return nums;
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
if (nums == null) return null;
//复制
int[] cp = new int[nums.length];
for(int i=0;i<cp.length;i++) cp[i]=nums[i];
//从最后一个元素开始,将其与前面的随机元素交换
Random rand=new Random();
for(int i=cp.length-1;i>=0;i--){
int j=rand.nextInt(i+1);
int tmp=cp[i];
cp[i]=cp[j];
cp[j]=tmp;
}
return cp;
}
}
/**
* 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();
*/
2.最小栈
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); –> 返回 -3.
minStack.pop();
minStack.top(); –> 返回 0.
minStack.getMin(); –> 返回 -2.
langage Java
class MinStack {
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
}
public void pop() {
}
public int top() {
}
public int getMin() {
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
思路
如果要在常数时间内检索到最小元素,需要有一个最小栈,每次入栈操作时,出栈,然后将最小值入栈,当取最小值时只需要出栈即可
解法
java 解法
class MinStack {
Stack<Integer> stack;
Stack<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
stack=new Stack<>();
minStack=new Stack<>();
}
public void push(int x) {
stack.push(x);
if(minStack.isEmpty()){
minStack.push(x);
}else{
Integer e=minStack.peek();
if(e>x){
minStack.push(x);
}else{
minStack.push(e);
}
}
}
public void pop() {
if(!stack.isEmpty()){
minStack.pop();
stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/