【原創】27. Remove Element ---leetcode算法筆記

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.

思路:遍歷nums,0~len-1爲最後返回的數組,len~i爲忽略數組。若第i個數不等於val,則需要把這個數移動len處,同時len加1,由於len~i忽略,所以i處可以不做任何處理。

Java代碼:

 

</pre><pre name="code" class="java">public int removeElement(int[] nums, int val) {
        if(nums.length <= 0) return 0 ;
        int len = 0 ;
        for(int i = 0 ;i < nums.length ;i ++){
            if(nums[i] != val) nums[len++] = nums[i] ;
        }
        return len ;
    }

上述算法是對不等於val的數做處理,若當不等於val的數的數量遠大於等於val的數量時,可選擇對等於val的數做處理,即,遍歷數組,遇到等於val的數就講該數移到當前有效數組的末尾。由於題目不要求按原序返回數組,所以此方法可行。

 

java代碼:

 

public int removeElement(int[] nums, int val) {
        if(nums.length <= 0) return 0 ;
        int i = 0;
        int len = nums.length ;
        while (i < len) {
            if (nums[i] == val) {
                nums[i] = nums[len - 1];
                len--;
            }
            else
                i++;
        }
        return len;
    }

 

 

 

 

 

 

 

 

 

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