the previous numbers

For an array, for each element, find the value of the first smaller element before it. If not, then output it itself.

Example

Given arr = [2,3,6,1,5,5], return [2,2,3,1,1,1].

Explanation:
According to the meaning, find the first smaller element in front of each number.

Given arr = [6,3,1,2,5,10,9,15], return [6,3,1,1,2,5,5,9].

Explanation:
According to the meaning, find the first smaller element in front of each number.

class Solution {
public:
    /**
     * @param num: The arry you should handle
     * @return: Return the array
     */
    vector getPreviousNumber(vector &num) {
        // Write your code here
        stack s;
        vector res;
        for (int i = 0; i < num.size(); i++) {
            while (!s.empty() && s.top() >= num[i]) {
                s.pop();
            }
            if (s.empty()) {
                res.push_back(num[i]);
            } else {
                res.push_back(s.top());
            }
            s.push(num[i]);
        }
        return res;
    }
};

你可能感兴趣的:(基础-栈)