remove element

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.

说明:

给定一个数组和一个数字val,删除数组中等于val的值,返回删除后的数组长度,返回长度之后的值都会被忽略

思路:

构建一个新的数组,将!=val的值都放入这个新的数组中,同时计数放入新数组的数量,返回这个数量的值

代码一(9ms):

public class Solution {
    public int removeElement(int[] nums, int val) {
        int[] o = new int[nums.length];
        int index = 0;
        for (int n : nums) {
            if (n != val) {
                o[index] = n;
                index++;
            }
        }
        System.arraycopy(o, 0, nums, 0, index );
        return index;
    }
}