算法作業HW26:LeetCode 27. Remove Element

Description:

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.


 

Note:

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.


Solution:

  Analysis and Thinking:

給定一個數組以及一個目標值,移除數組中所有與該值相等的元素,並返回移除後數組長度。與26一樣,通過理解題意以及輸入數組長度,設置循環即可解決


  Steps:

1. 設置記錄變量count

2. 遍歷數組,如果當前值與目標值相等,count加一,跳過,相當於移除

3. 如果當前值與目標值不等,設置當前位置減去count下標的位置的元素爲當前元素,

4. 不斷重複,最後構造了一個新的不包含目標值的數組

5  返回數組長度減去count的值,即結果,因爲count代表了等於目標值的元素個數


Codes:


class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
    int count = 0;
    for(int i = 0 ; i < nums.size() ; ++i) {
        if(nums[i] == val)
            count++;
        else
            nums[i-count] = nums[i];
    }
    int result = nums.size()-count;
    return result;
}
};


Results:




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