Leetcode OJ 27 Remove Element [Easy]
题目描述:
Given anarray and a value, remove all instances of that value in place and return thenew length.
Do notallocate extra space for another array, you must do this in place with constantmemory.
Theorder of elements can be changed. It doesn't matter what you leave beyond thenew length.
Example:
Giveninput array nums = [3,2,2,3], val = 3
Yourfunction should return length = 2, with the first two elements of nums being 2.
题目理解:
给定一个数组和一个数值,移除数组中所有所给的数值,返回新数组的长度。
测试用例:
功能测试:数组中有存在1个、2个、多个所给数值;
边界测试:数组是null;数组长度是1;数组中所有的数字都是所给数字;数组中不存在所给数值;
分析:
1. 维护两个指针,check从数组头开始向后遍历,add从数组尾开始向前移动,Add向前移动,所指的数字不等于所给的val;
2. check从头开始遍历,如果所指的数字是val,则用add所指的值替换,add所指的位置的数字删去(在leetcode这道题中,将其替换为val即可通过),add向前移动(一直前移直到所值数字不等于val),check后移一位继续判断;
3. 直到check的移动到add的后面为止,此时add + 1是新数组的长度;
解答:
class Solution {
public int removeElement(int[] nums, intval) {
int check= 0,add = nums.length - 1;
while(add> 0 &&nums[add] == val){
add --;
}
if(add== 0){
if(nums[add]== val) return 0;
else return 1;
}
while(add> 0 &&check < nums.length -1&& check <= add){
if(nums[check]== val){
nums[check] = nums[add];
check ++;
nums[add] = val;
while(nums[add] == val) add --;
}
else{
check ++;
}
}
return add + 1;
}
}