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

翻译:给定一个数组和一个值,移除数组中为该值的元素,返回新的数组长度。(其实是原数组的长度减去特定值个数)

但是不能占用额外的空间来另声明一个数组,必须在O(1)的内存占用中做完。

元素的顺序可以更改~新数组尾部是什么不重要。

Example:

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

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

答案

class Solution {
public int removeElement(int[] nums, int val) {
if (nums.length==0) return 0; //特殊情况
int j=0;
for (int i=0;i<nums.length;i++){
if (nums[i]!=val){//和给定值不相等就留下
nums[j]=nums[i];
j++;
}
}
return j;
}
}

posted @ 2018-01-18 13:12  同销万古愁  阅读(105)  评论(0编辑  收藏  举报