the previous numbers

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36346463/article/details/80501698

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<int> getPreviousNumber(vector<int> &num) {
        // Write your code here
        stack<int> s;
        vector<int> 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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_36346463/article/details/80501698