27. Remove Element ---leetcode算法笔记

来源:互联网 发布:windows10下载不了软件 编辑:程序博客网 时间:2024/05/22 04:52

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.

思路:遍历nums,0~len-1为最后返回的数组,len~i为忽略数组。若第i个数不等于val,则需要把这个数移动len处,同时len加1,由于len~i忽略,所以i处可以不做任何处理。

Java代码:

</pre><pre name="code" class="java">public int removeElement(int[] nums, int val) {        if(nums.length <= 0) return 0 ;        int len = 0 ;        for(int i = 0 ;i < nums.length ;i ++){            if(nums[i] != val) nums[len++] = nums[i] ;        }        return len ;    }
上述算法是对不等于val的数做处理,若当不等于val的数的数量远大于等于val的数量时,可选择对等于val的数做处理,即,遍历数组,遇到等于val的数就讲该数移到当前有效数组的末尾。由于题目不要求按原序返回数组,所以此方法可行。

java代码:

public int removeElement(int[] nums, int val) {        if(nums.length <= 0) return 0 ;        int i = 0;        int len = nums.length ;        while (i < len) {            if (nums[i] == val) {                nums[i] = nums[len - 1];                len--;            }            else                i++;        }        return len;    }




0 0