(细节题)[LeetCode]Remove Element
原创
©著作权归作者所有:来自51CTO博客作者byamao1的原创作品,请联系作者获取转载授权,否则将追究法律责任
Question:
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.
本题难度easy。我自己写的方法比较ugly,贴上以供compare:
public class Solution {
public int removeElement(int[] nums, int val) {
//require
if(nums==null)
return 0;
int size=nums.length;
if(size<1)
return 0;
Arrays.sort(nums);
//invariant
int s=-1,count=0;
for(int i=0;i<size;i++){
if(nums[i]==val){
if(s==-1)
s=i;
count++;
}
}
//there is not val in nums
if(s==-1)
return size;
for(int i=0;i<size-s-count;i++){
nums[s+i]=nums[s+i+count];
}
//ensure
return size-count;
}
}
【推荐】下面这个是比较优美的,而且是一趟完成的:
public class Solution {
public int removeElement(int[] nums, int val) {
//require
if(nums==null)
return 0;
int size=nums.length;
if(size<1)
return 0;
//invariant
int index = 0;
for (int i = 0; i < size; ++i) {
if (nums[i] != val) {
nums[index++] = nums[i];
}
}
//ensure
return index;
}
}