leetcode27. 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.

Subscribe to see which companies asked this question.

思路

先排序,然後剩下的思路跟26題類似。

測試用例

[3,2,2,3]  3
[]  3
[2, 2, 2, 2, 2, 2, 2] 3
[2, 2, 2, 2, 2, 2, 3] 3

#代碼

public class Solution {
    public int removeElement(int[] nums, int val) {
        int i = 0;
        Arrays.sort(nums);
        for(int n= 0; n < nums.length; n++){

            if(nums[n] == val)
                continue;
            nums[i++] = nums[n];

        }

        return i;
    }
}

結果

這裏寫圖片描述

他山之玉

public int removeElement(int[] A, int elem) {
    int len = A.length;
    for (int i = 0 ; i< len; ++i){
        while (A[i]==elem && i< len) {
            A[i]=A[--len];
        }
    }
    return len;
}
//c++
int removeElement(int A[], int n, int elem) {
    int i = 0;
    while (i < n) {
        if (A[i] == elem) {
            A[i] = A[n - 1];
            n--;
        }
        else
            i++;
    }
    return n;
}
#python
  def removeElement(self, nums, val):
    start, end = 0, len(nums) - 1
    while start <= end:
        if nums[start] == val:
            nums[start], nums[end], end = nums[end], nums[start], end - 1
        else:
            start +=1
    return start
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章