[503] Next Greater Element II [Medium]
给一个循环数组,找到离当前元素最近的比它大的元素。
Input: [1,2,1] Output: [2,-1,2] Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.
我的思路:直接暴力解。
1 class Solution { 2 public: 3 vector<int> nextGreaterElements(vector<int>& nums) { 4 vector<int> ans(nums.size(), -1); 5 for(auto i = 0; i < nums.size(); ++i) { 6 bool flag = false; 7 for(auto j = i + 1; j < nums.size(); ++j) { 8 if (nums[j] > nums[i]) { 9 ans[i] = nums[j]; 10 flag = true; 11 break; 12 } 13 } 14 if (flag == false) { 15 for (auto j = 0; j < i; ++j) { 16 if (nums[j] > nums[i]) { 17 ans[i] = nums[j]; 18 flag = true; 19 break; 20 } 21 } 22 } 23 } 24 return ans; 25 } 26 };
[150] Evaluate Reverse Polish Notation [Medium]
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
注意一下弹出的顺序,不要写错了(- 和 / 对于操作数有顺序之分)
1 class Solution { 2 public: 3 int evalRPN(vector<string>& tokens) { 4 stack<int> stk; 5 int x, y; 6 for (auto token : tokens) { 7 if (token == "+" || token == "-" || token == "*" || token == "/") { 8 x = stk.top(); 9 stk.pop(); 10 y = stk.top(); 11 stk.pop(); 12 if (token == "+") x = x + y; 13 if (token == "-") x = y - x; 14 if (token == "*") x = x * y; 15 if (token == "/") x = y / x; 16 stk.push(x); 17 } else { 18 int t = stoi(token); 19 stk.push(t); 20 } 21 } 22 int ans = stk.top(); 23 return ans; 24 } 25 };