2017年5月18日 星期四

Remove Element

Leetcode easy題(嗯,真的很easy)
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        while( haveVal(nums, val) ) {
            nums.erase(std::find(nums.begin(), nums.end(), val));
        }
        return nums.size();
    }
private:
    bool haveVal(vector<int> nums, int val) {
        for(int i=0; i<nums.size(); i++) {
            if(nums.at(i) == val) return true;
        }
        return false;
    }
};
重點在善用STL幫助你省事,畢竟C++的各個容器都並非非常完整、操作簡單的那種東西
相反的它非常鼓勵各個組件組合應用這種形式
By the way,Algorithm中的幾個方法還不如像這樣自行實現方便,因為他們被設計成適合解泛化問題的形式

ps. Python只要這樣寫就行了,選錯工具,誤你一生(誤www)
def removeElement(list, val):
    while val in list:
        list.remove(val)
    return len(list)

這則是利用了find的版本,可以看得出來有些冗長
public:
    int removeElement(vector<int>& nums, int val) {
        while(std::find(nums.begin(), nums.end(), val) != nums.end()) {
            nums.erase(std::find(nums.begin(), nums.end(), val));
        }
        return nums.size();
    }

沒有留言:

張貼留言