Kodewick
開始學 →
基礎←→0 / 86

買得起的

#024基礎if (p <= budget) push_back約 4 分鐘

逛超市時只看買得起的東西。寫 cheap_ones(prices, budget):把不超過 budget 的價錢按原來的順序放進一個新的 vector 返回。一個都沒有就返回空的。

示例
cheap_ones({3, 12, 5, 20}, 10)→[3, 5]
cheap_ones({8, 9}, 5)→[]
函式vector<int> cheap_ones(const vector<int> &prices, int budget)
main.cpp
#include <vector>
using namespace std;

vector<int> cheap_ones(const vector<int> &prices, int budget) {
    vector<int> picked;
    for (int p : prices) {
        // 在這裡寫:p 不超過 budget,就放進 picked
    }
    return picked;
}
Ctrl + Enter 也能執行
結果

寫好了先點「執行」試試示例,沒問題再點「提交」。