Rrui的Leetcode刷題筆記(五)
阿新 • • 發佈:2018-12-18
225. 用佇列實現棧
class MyStack { public: /** Initialize your data structure here. */ queue<int> a; int k=0; MyStack() { } /** Push element x onto stack. */ void push(int x) { a.push(x); k++; } /** Removes the element on top of the stack and returns that element. */ int pop() { int p=--k; while(p--) { int q=a.front(); a.pop(); a.push(q); } int q=a.front(); a.pop(); return q; } /** Get the top element. */ int top() { int p=k; int q; while(p--) { q=a.front(); a.pop(); a.push(q); } return q; } /** Returns whether the stack is empty. */ bool empty() { return a.empty(); } }; /** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * bool param_4 = obj.empty(); */
315. 計算右側小於當前元素的個數
class Solution { public: vector<int> countSmaller(vector<int>& nums) { vector<int> counts(nums.size()); vector<int> trans; if (nums.size() == 0) return counts; trans.push_back(nums[nums.size() - 1]); for (int i = nums.size() - 2; i >= 0; i--) { // 這裡二分我們用STL裡的就好了 auto it = lower_bound(trans.begin(), trans.end(), nums[i]); counts[i] = it - trans.begin(); trans.insert(it, nums[i]); } return counts; } };