1365. 有多少小於當前數字的數字

題目鏈接

暴力法

class Solution {
public:
    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
        //方法1 暴力求解
        int n = nums.size();
        vector<int> res(n);
        for(int i = 0; i < n; i++){
            for(auto x: nums) 
                if(x < nums[i]) res[i]++;
        }
        return res;
    }
};

動態規劃

class Solution {
public:
    vector<int> smallerNumbersThanCurrent(vector<int>& nums) {
        //方法2 動態規劃
        int input[101]{0}, output[101]{0};
        for(auto x: nums) input[x]++;
        for(int i = 1; i <= 100; i++){
            output[i] = output[i-1] + input[i-1]; //累計的數量 加上 前一個數的數量 因爲在output[i-1]中沒有計算這個值
        }
        vector<int> res;
        for(auto x: nums) res.push_back(output[x]); 
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章