您的位置:首页 > 编程语言 > Java开发

Remove Element leetcode java

2015-12-14 16:54 190 查看
问题描述:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: