问题:
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的值一次复制到数组的前面,而不必管后面是什么。耗时11ms.
public class Solution {
public int removeElement(int[] nums, int val) { int len = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] != val){ nums[len++] = nums[i]; } } return len; } }②使用count记录数组中值为val的个数,将非val的数向前移动count个位数即可。耗时9ms.
public class Solution {
public int removeElement(int[] nums, int val) { int count = 0;//记录val值的个数 for(int i = 0; i < nums.length; i++) { if(nums[i] == val){ count ++; }else{ nums[i - count] = nums[i]; } } return nums.length - count; } }