设计问题
shuffle an array
直接copy了别人的代码,用了库函数random_shuffle(iterator1,iterator2)
代码:
class Solution {
public:
vector<int> m_nums;
Solution(vector<int> nums) : m_nums(nums){
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return m_nums;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
vector<int> temp(m_nums);
random_shuffle(temp.begin(),temp.end());
return temp;
}
};
最小栈
也是copy的代码,需要好好理解。
来一个,如果符合比目前最小的更小,就入min。
出栈的时候,如果不是目前最小,就一般出,否则min也出。
AC代码:
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
s.push(x);
if(min.empty()||min.top()>=x)
min.push(x);
}
void pop() {
if(min.top()==s.top())
min.pop();
s.pop();
}
int top() {
return s.top();
}
int getMin() {
return min.top();
}
private:
stack<int> s;
stack<int> min;
};
博客围绕LeetCode初级算法展开,涉及shuffle an array和最小栈两个问题。对于数组洗牌,使用库函数random_shuffle实现;最小栈问题通过特定入栈和出栈规则处理,代码均为复制,需进一步理解。
571

被折叠的 条评论
为什么被折叠?



