题意:对指定的数组删除所有的指定的值。并返回新的长度。
初步分析:
因为必须在本数组上完成操作。所以在本数组上设立两个指针。
两个指针,一个遍历旧数组,一个遍历新数组。旧数组的遍历值和给出的值比较,如果相同,略过。如果不同,赋值给新数组的指针,然后新数组指针才往后走。
直接上手写代码:
public class Solution {
public int removeElement(int[] nums, int val) {
int newpoint = 0;
int oldpoint = 0;
if(nums.length == 0)
return 0;
while(oldpoint < nums.length)
{
if(val != nums[oldpoint])
{
nums[newpoint] = nums[oldpoint];
newpoint++;
}
oldpoint++;
}
return newpoint++;
}
}
再来看看那别人的(Psychochen),简练呀:
public class Solution {
public int removeElement(int[] nums, int val) {
int index = 0;
for (int i = 0; i < nums.length; i++)
if (nums[i] != val)
nums[index++] = nums[i];
return index;
}
}