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

Example:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

 

从一个数组中删除指定元素,而且也只能在当前数组中操作。这跟Remove Duplicates from Sorted Array一样的要求,所以思路也差不多。就是用两个指针,一个用于遍历,一个代表新数组添加元素。这题比去除重复元素那题要简单。

 

class Solution {
    public int removeElement(int[] nums, int val) {
        if(nums==null||nums.length==0)
            return 0;
        int count=0;//该指针用于添加元素,i用于遍历数组
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=val)
                nums[count++]=nums[i];
        }
        return count;
    }
}

 


posted on 2017-12-19 10:05  夜的第八章  阅读(122)  评论(0编辑  收藏  举报

导航