题目:Remove Element
难度:easy
问题描述:
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.
解题思路:一道easy题,很简单,但是要注意,若是返回n,则nums的前n位需要是所有未被剔除的数。此外,不能使用额外的空间。
具体代码如下:
public class Solution {
public int removeElement(int[] nums, int val) {
if(nums==null) return 0;
Arrays.sort(nums);
int[]p=nums;
int res=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==val){
}else{
p[res]=nums[i];
res++;
}
}
return res;
}
}