问题描述:
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
问题分析:给定一个数组,一个value值,从这个数组中删除所有值为value的元素,并返回数组length
算法:
方法一:借助另外一个list,耗费空间
public static int removeElement(int nums[],int val){ List<Integer> list = new ArrayList<Integer>(); //将数据暂时存放在list中 for (int i = 0; i < nums.length; i++) { if(nums[i] != val) list.add(nums[i]); } if(list.size() != 0){ for (int i = 0; i < list.size(); i++) { //再将list中的数据写回数组中 nums[i] = list.get(i); } } return list.size() ; //返回数组length }
方法二:采用两个指针,不需要额外空间,数组原地做修改
public int removeElement(int[] nums, int val) { //原地修改,不需要额外的空间 int newindex = 0; for (int i = 0; i < nums.length; i++) { if(nums[i] != val) nums[newindex++] = nums[i]; } return newindex; }