题目描述
- 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 by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length. - Examlple :
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
问题分析
- 该题大意便是将给定的元素 val 全部从一个数组中“删除”掉,返回删除后的数组的长度,要求不能用空间复杂度O(1)
- 其实该题和LeetCode 283.Move Zeroes很像,只不过那题是指定的元素为0,然后将非0元素放在前面,0元素全部放在后面。而这道题,是将 非 val数据放在前面即可,然后统计出非val的所有个数,返回。所以具体方法和 283 题类似,如下:
- 直接用覆盖的方式,缺点:只得到非val个数,无法将val放在后面(除非再度遍历一次)
- 用交换的方式(当然,也不是严格两数交换)。可以讲非val数据放在前面(并能保证稳定性),且能将 val 数据放在后面
- 用 p q前后指针实现交换,缺点:不能保证稳定性
经验教训:
- 这种题型是对一个数组进行原地操作,使得一部分数据(满足某一标准)在前面,另一部分数据(不满足该标准)在后面,并使得前部分数据保持原有顺序(稳定性)。
双指针做法
代码实现
- 覆盖的方式:
public int removeElement(int[] nums, int val) {
if (nums == null || nums.length == 0) {
return 0;
}
int k = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[k++] = nums[i];
}
}
return k;
}
- “交换”的方式(推荐)
public int removeElement(int[] nums, int val) {
if (nums == null || nums.length == 0) {
return 0;
}
int k = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
if (i != k) {
//swap(nums, i, k++);
nums[k++] = nums[i];
nums[i] = val;
}else {
k++;
}
//nums[k++] = nums[i];
}
}
return k;
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
- p,q前后指针方法(不能保证稳定性)
public int removeElement(int[] nums, int val) {
if (nums == null || nums.length == 0) {
return 0;
}
int p = 0;
int q = nums.length - 1;
while (p <= q) {
if (nums[p] != val) {
++p;
}else if (nums[q] == val) {
--q;
}else {
swap(nums, p++, q--);
}
}
return p;
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}