using vector C++ 6m O(n) complexity


  • 0

    Things that needs to be careful is

    1. to store the sum of the last two numbers into the list when option "+" happens
    2. to store the result into the list when option "D" happens
    using namespace std;
    
    class Solution {
    public:
        int calPoints(vector<string>& ops) {
            vector<int> holder;
            int sum = 0;
            
            for(string s : ops)
            {
                if(s == "+")
                {
                    int firstNum = holder[holder.size()-1];
                    int secondNum = holder[holder.size()-2];
                    int result = firstNum + secondNum;
                    
                    // got to store the current sum 
                    // from the last two numbers into the list
                    holder.push_back(result);
                    
                    sum += result;
                }
                else if(s == "C")
                {
                    sum -= holder[holder.size()-1];
                    holder.pop_back();
                }
                else if(s == "D")
                {
                    int number = holder[holder.size()-1] * 2;
                    holder.push_back(number);
                    sum += number;
                }
                else
                {
                    int number = stoi(s);
                    sum += number;
                    holder.push_back(number);
                }  
            }
            
            return sum;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.