27.Remove Element

【题目】

Given an arraynums_and a value_val, 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 by modifying the input array in-place with O(1) extra memory.

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

給定一個數組nums和一個值val,你需要原地移除所有數值等於val的元素,返回移除後數組的新長度。

不要使用額外的數組空間,你必須在原地修改輸入數組並使用O(1)額外空間的條件下完成。

元素的順序可以改變。你不需要考慮數組中超出新長度後面的元素。

Example:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

【思路】

那時候我沒有看清楚題目,沒有看到 It doesn't matter what you leave beyond the new length.

導致我一直在想List內其餘的值和順序,後來看其他人的解才想說『咦 那些多的不用管嗎?』,

解法就先跑該List的迴圈,如果迴圈該值不等於Target值,就表示該值非需移除值,

就直接占用List內的空間依序放下非移除值,即可完成。

【解法】

☆JAVA

class Solution {
    public int removeElement(int[] nums, int val) {
        int retunrnVal = 0;
        if(null != nums && nums.length >0){
            for(int i = 0;i<nums.length;i++){
                if(nums[i] != val){                    //如果為非需移除值
                    nums[retunrnVal] = nums[i];        //佔用該List內的位置
                    retunrnVal++;                      //同時紀錄長度    
                }
            }
        }
        return retunrnVal;
    }
}

☆Python

class Solution:
def removeElement(self, nums, val):
    length = 0
    for i in range(len(nums)):
        if nums[i] != val:                #如果為非需移除值
            nums[length] = nums[i]        #佔用該List內的位置
            length += 1                   #同時紀錄長度    
    return length

results matching ""

    No results matching ""