leetcode:27 Remove Element-每日編程第二十一題

Remove Element

Total Accepted: 89646 Total Submissions: 276815 Difficulty: Easy

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

思路:

1).注意一點nums.erase(it)後,會自動遞增it,使得it指向vector的下一個值,此時,如果是for循環中寫了it++,就會跳過這個值。因此,it++要寫在函數體內。

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int size = nums.size();
        for(vector<int>::iterator it = nums.begin();it!=nums.end();){
            if(*it==val){
                nums.erase(it);
                size--;
            }else{
                it++;
            }
        }
        return size;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章