Saturday, January 16, 2016

Leetcode: Implement Stack using Queues

Implement Stack using Queues

My Submissions
Total Accepted: 28206 Total Submissions: 92981 Difficulty: Easy
Implement the following operations of a stack using queues.
  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.
Notes:
  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.
Subscribe to see which companies asked this question
Hide Tags
 Stack Design
Show Similar Problems


































------------------------------------------------------------------------

stack.pop() using queue.pop():

using queue to push its front values to back until the original back one! Then pop the current front one.


////////////////////////////////////////////////////////////////////////////
class Stack {
public:
    queue<int> que;
    // Push element x onto stack.
    void push(int x) {
        que.push(x);
    }

    // Removes the element on top of the stack.
    void pop() {
        //using queue itself to push all front values to back until the last one
        for (int i=0;i<que.size()-1;i++){
            que.push(que.front());
            que.pop();
        }
        que.pop();
    }

    // Get the top element.
    int top() {
        return que.back();
    }

    // Return whether the stack is empty.
    bool empty() {
        return que.empty();
    }
};





Friday, January 15, 2016

Leetcode: Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation

My Submissions
Total Accepted: 57639 Total Submissions: 254722 Difficulty: Medium
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +-*/. Each operand may be an integer or another expression.
Some examples:
  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Subscribe to see which companies asked this question
Hide Tags
 Stack
Show Similar Problems





















----------------------------------------------------------------------------------

思路:

典型的stack问题。逐一扫描每个token,如果是数字,则push入stack,如果是运算符,则从stack中pop出两个数字,进行运算,将结果push回stack。最后留在stack里的数即为最终结果。

以题中例子说明

exp:     2    1      +    3      *
stack:   2    2,1   3    3,3   9


///////////////////////////////////////////////////////////////////////
class Solution {
 public:
        int evalRPN(vector<string>& tokens) {
               stack<int> tokTmp;
               for (int i = 0; i<tokens.size(); i++){
                      //tokens[i] is a string, so "" is used!
                      if ((tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")){
                            int y = tokTmp.top();
                            tokTmp.pop();
                            int x = tokTmp.top();
                            tokTmp.pop();
                            if (tokens[i] == "+")tokTmp.push(x + y);
                            else if (tokens[i] == "-")tokTmp.push(x - y);
                            else if (tokens[i] == "*")tokTmp.push(x*y);
                            else if (tokens[i] == "/")tokTmp.push(x / y);
                      }
                      else {
                            int x = stoi(tokens[i], nullptr, 10);
                            tokTmp.push(x);
                      }
               }
               return tokTmp.top();
        }

 };










Leetcode: Min Stack

 Min Stack

My Submissions
Total Accepted: 57566 Total Submissions: 271279 Difficulty: Easy
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.
Subscribe to see which companies asked this question
Hide Tags
 Stack Design
Show Similar Problems




















--------------------------------------------------------------------------
Keep two stacks inside: one store all and the other store the minimal.
Note: only the current x is smaller or equal to the mimStack.top() is saved.



///////////////////////////////////////////////////////////
class MinStack {

public:
    void push(int x) {
        curSta.push(x);
        if(minSta.empty() || x<=minSta.top() )
           minSta.push(x);
    }

    void pop() {
       
        if(minSta.top() == curSta.top() )
            minSta.pop();
        curSta.pop(); //Note: this line should be put in last, otherwise, the above codes can not be compared!!!!       
    }

    int top() {
        return curSta.top();
    }

    int getMin() {
        return minSta.top();
    }
   
private:
    stack<int> minSta;
    stack<int> curSta;  
};







Tuesday, January 12, 2016

Leetcode: Permutations II

Permutations II

My Submissions
Total Accepted: 58417 Total Submissions: 216886 Difficulty: Medium
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].
Subscribe to see which companies asked this question
Hide Tags
 Backtracking
Show Similar Problems

















-------------------------------------------------------------------------------------

BT.
Same as Permutations I. 
Note: 

vector<int>::iterator it = vt.begin();
vt.insert(it, nums[i]);
//insert a val before 'it'! In the end, it=vt.end(), (it)[0] will be wrong!!

SO use following:
vector<int>::iterator pre = it - 1;
vt.insert(pre, nums[i]);

////////////////////////////////////////////////////////////////////////
class Solution {
 public:
        void backTrac(vector<int>& nums, vector<vector<int>> &result, vector<vector<int>> &tmp, int i){
               if (i <= 0){ //when nums.size()==1
                      vector<vector<int>> tmp1;
                      vector<int> vTmp;
                      vTmp.push_back(nums[i]);
                      tmp1.push_back(vTmp);
                      tmp = tmp1;
                      result = tmp;//when nums.size()==1
                      return;

               }
               else{
                      backTrac(nums, result, tmp, i - 1);

                      //insertion
                      vector<vector<int>> tmp1;
                      for (int m = 0; m<tmp.size(); m++){
                            for (int n = 0; n <= tmp[m].size(); n++){

                                   vector<int> vt;
                                   vt = tmp[m];
                                   vector<int>::iterator it = vt.begin();
                                   it = it + n;
                                   if (i == nums.size()) break;

                                   //vt.insert(it, nums[i]);
                                   if (n == 0) vt.insert(it, nums[i]);
                                   else {
                                          vector<int>::iterator pre = it - 1;
                                          if (((pre)[0]) != nums[i])vt.insert(it, nums[i]); //insert a val before it! In the end, it=vt.end(), (it)[0] will be wrong!!
                                          else break;
                                   }
                                   tmp1.push_back(vt);
                            }
                      }
                      tmp = tmp1;
                      result = tmp;
               }
        }

        vector<vector<int>> permuteUnique(vector<int>& nums) {
               vector<vector<int>> result, tmp;
               if (nums.size() == 0)return result;
               int i = nums.size() - 1;
               backTrac(nums, result, tmp, i);
               return result;
        }

 };















Friday, January 8, 2016

Leetcode: Permutations

46. Permutations

My Submissions
Total Accepted: 81411 Total Submissions: 239626 Difficulty: Medium
Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].
Subscribe to see which companies asked this question
Hide Tags
 Backtracking
Show Similar Problems


















BT problem:
Using the similar method as SUBSET. Composing the subsets by insertion.




//////////////////////////////////////////////
class Solution {
 public:
        void backTrac(vector<int>& nums, vector<vector<int>> &result, vector<vector<int>> &tmp, int i){
               if (i == 0){
                      vector<vector<int>> tmp1;
                      vector<int> vTmp;
                      vTmp.push_back(nums[i]);
                      tmp1.push_back(vTmp);
                      tmp = tmp1;
                      result = tmp;
                      return;

               }
               else{
                      backTrac(nums, result, tmp, i - 1);
                      
                      //insertion
                      vector<vector<int>> tmp1;
                      for (int m = 0; m<tmp.size(); m++){
                            for (int n = 0; n<=tmp[m].size(); n++){

                                   vector<int> vt;
                                   vt = tmp[m];
                                   vector<int>::iterator it = vt.begin();
                                   it = it + n;
                                   if (i == nums.size()) break;
                                   vt.insert(it, nums[i]);
                                   tmp1.push_back(vt);
                            }
                      }
                      tmp = tmp1;
                      result = tmp;
               }
        }

        vector<vector<int>> permute(vector<int>& nums) {
               vector<vector<int>> result, tmp;
               int i = nums.size() - 1;
               backTrac(nums, result, tmp, i);
               return result;
        }

 };