Leetcode 27 Remove Element

題目要求:

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

Do not allocate extra space for another array, you must do this in place with constant memory.

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

Example:
Given input array nums = [3,2,2,3]val = 3

Your function should return length = 2, with the first two elements of nums being 2.

--------------------------------------------------------------------------------------------------------------------------------------------------------------

解法一:

利用迭代器iterator,遍歷數組,找到=val的元素,就刪除

代碼如下:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        vector<int>::iterator i;
        if(nums.size() == 0)
            return 0;
        while((i = find(nums.begin(), nums.end(), val)) != nums.end())
            nums.erase(i);
        return nums.size();
    }
};

解法二:

參考了網上的解法,利用兩個指針分別指向數組的開頭和末尾,如果末尾元素!=val,開頭元素==val,則用末尾元素替換掉開頭元素,然後末尾元素指針--,開頭元素指針++;如果末尾元素==val,則將末尾元素指針--;如果都!=val,則將開頭元素指針++;最後返回數組元素個數即可

代碼如下:

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int size = nums.size();
        if(size == 0)
            return 0;
        int low = 0;
        int high = size - 1;
        
        int count = 0;
        
        while(low <= high)
        {
            if(nums[high] == val)
            {
                high--;
                count++;
                continue;
            }
            if(nums[low] == val)
            {
                count++;
                nums[low] = nums[high];
                low++;
                high--;
            }
            else
            {
                low++;
            }
        }
        return size-count;
    }
};


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