[leetcode初级算法]设计问题总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/summer2day/article/details/83719372

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();

思路:

每一个位置都有可能跟剩下的n-1个位置进行交换

c++代码:

class Solution {
public:
    Solution(vector<int> nums) {
        vec=nums;
    }
    
    /** Resets the array to its original configuration and return it. */
    vector<int> reset() {
        return vec;
    }
    
    /** Returns a random shuffling of the array. */
    vector<int> shuffle() {
        vector<int> tmp=vec;
        for(int i=0;i<vec.size();i++)
        {
            int j=rand()%vec.size();
            //交换tmp[i],tmp[j]
            int t=tmp[i];
            tmp[i]=tmp[j];
            tmp[j]=t;
        }
        return tmp;
    }
    vector<int> vec;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * vector<int> param_1 = obj.reset();
 * vector<int> param_2 = obj.shuffle();
 */

最小栈

设计一个支持 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.

思路:

创建两个stack,一个存储所有值,一个存储最小值

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        s1.push(x);
        if(s2.empty()||s2.top()>=x)//注意这个等号,测试用例:入栈0 1 0,出栈0 1 
            s2.push(x);
    }
    
    void pop() {
        if(s1.top()==s2.top())
            s2.pop();
        s1.pop();
        
    }
    
    int top() {
        return s1.top();
    }
    
    int getMin() {
        return s2.top();
    }
    stack<int> s1,s2;
};

/**
 * 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();
 */

猜你喜欢

转载自blog.csdn.net/summer2day/article/details/83719372