Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
思路:本题题意是移除某个数。设置两个指针i,j一个指向数组的开始,一个指向数组的结尾。然后将i向后遍历,如果发现等于val则将它与j指向的位置元素对调。
一直到i>j的时候。这个数组不含val的元素个数是j;
代码如下(已通过leetcode)
public class Solution {
public int removeElement(int[] nums, int val) {
int length=nums.length;
int i=0;
int j=length-1;
while(i<=j) {
if(nums[i]==val) {
nums[i]=nums[j];
nums[j]=val;
j--;
} else i++;
}
return j+1;
}
}