##LeetCode—27. Remove Element
####题目
https://leetcode.com/problems/remove-element/description/
给出一个数组和一个val,要求找出数组中的val,并将不等于val的值移动到数组的前段,至于后面是什么数值可以不关心,返回不等于val的元素的个数。要求不能增加新的存储空间,空间复杂度为1.
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
####思路及解法
设置两个指针,一个j用来标记已经调整好的数组的下一个位置,一个指针i用来循环遍历数组,i一旦遇到不等于val的元素,就将钙元素与j标记的元素进行互换,然后j++。这样就能保证j标记的前一个位置的元素总是不等于val的,最后只要返回j就可以了。
好好体会下两个指针是相互不影响的移动的。
####代码
class Solution {
public int removeElement(int[] nums, int val) {
int j = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] != val){
nums[j] = nums[i];
j++;
}
}
return j;
}
}