leetcode 27. Remove Element

来源:互联网 发布:汉族智商 知乎 编辑:程序博客网 时间:2024/06/06 06:41

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.

题目的意思是,既要返回newLength,又要使得原nums数组中的 [0,newLength) 项 为 去掉val后的数组。

简单题一个。

public int removeElement(int[] nums, int val) {int pointer=0;for(int i=0;i<nums.length;i++){if(nums[i]!=val){nums[pointer]=nums[i];pointer++;}}return pointer;}
这道题有solutions:https://leetcode.com/problems/remove-element/solution/

Solution


Approach #1 (Two Pointers) [Accepted]

This solution is very similar to the solution to Remove Duplicates from Sorted Array.

public int removeElement(int[] nums, int val) {    int i = 0;    for (int j = 0; j < nums.length; j++) {        if (nums[j] != val) {            nums[i] = nums[j];            i++;        }    }    return i;}

Complexity analysis

  • Time complexity : O(n)O(n). Assume the array has a total of nn elements, both ii and jj traverse at most 2n2n steps.

  • Space complexity : O(1)O(1).


Approach #2 (Two Pointers - when elements to remove are rare) [Accepted]

Intuition

考虑当数组几乎没有元素要移除的情况。比如, nums = [1,2,3,5,4], val = 4nums=[1,2,3,5,4],val=4. 之前的算法将会对前4个元素产生无谓的拷贝。再比如, nums = [4,1,2,3,5], val = 4nums=[4,1,2,3,5],val=4. 将元素 [1,2,3,5][1,2,3,5] 都向左移动一格 也是不必要的,可以直接把 4 和 5 交换一下位置即可(因为题干中说了“The order of elements can be changed”)。

Algorithm

当 nums[i] = valnums[i]=va时,我们将当前元素与最后元素交换,然后抛弃最后元素。

注意到:被交换到当前元素的 最后元素 也可能是你想要移除的元素,但是不用担心,i 并没有增加,你可以在下一次循环中再次检查该元素)

public int removeElement(int[] nums, int val) {    int i = 0;    int n = nums.length;    while (i < n) {        if (nums[i] == val) {            nums[i] = nums[n - 1];            // reduce array size by one            n--;        } else {            i++;        }    }    return n;}

Complexity analysis

  • Time complexity : O(n)O(n). Both ii and nn traverse at most nn steps. In this approach, the number of assignment operation is equal to the number of elements to remove. So it is more efficient if elements to remove are rare.

  • Space complexity : O(1)O(1).