Skip to content

27. Remove Element

Jacky Zhang edited this page Aug 8, 2016 · 1 revision

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.

Array类题目。

可采用与前一道remove duplicates相类似的思路,遇到value则跳过,否则将数组元素依次放置。 但是,在要删除元素稀少的情形下,这样会造成许多无谓的赋值操作。 注意到这里元素顺序可以改变,因此我们可以考虑一旦碰到值为value的元素,我们将数组末尾的数赋值过来。 这样,赋值操作即为value在数组中的个数。

public class Solution {
    public int removeElement(int[] nums, int val) {
        int i = 0;
        int last = nums.length-1;
        while(i <= last) {
            if(nums[i] == val) {
                nums[i] = nums[last--];
            } else {
                i++;
            }
        }
        return last+1;
    }
}
Clone this wiki locally