官方提示( C l a r i f i c a t i o n Clarification Clarification)真的具有误导作用,真要看还得看 E x a m p l e Example Example
Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: 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. For example if you return 2 with nums =
[2,2,3,3] or nums = [2,3,0,0], your answer will be accepted.
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3]
Explanation: 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.
与 LeetCode 26. Remove Duplicates from Sorted Array 不同的是
本题修改完元素位置后的数组,前面几个元素不一定要按照特定顺序排序
举个例子(用下面JAVA的两种方法打印修改后的数组)
int[] nums = new int[]{1,2,3,3,3,4,5,6}; // 原数组
System.out.println(test.removeElement(nums,3)); // 数组按顺序
System.out.println(test2.removeElement(nums,3)); // 数组不按顺序
// 打印数组
output:
[1, 2, 4, 5, 6]
[1, 2, 6, 5, 4]
JAVA
① 数组按顺序(快指针和慢指针)
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
}
② 数组不按顺序(双指针)
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
int n = nums.length; // 之所以不用 n = nums.length-1
while (i < n) { // 是因为 while循环要模仿 for循环迭代到 nums.length
if (nums[i] == val) {
nums[i] = nums[n - 1];
n--;
} else {
i++;
}
}
return n;
}
}
Python
① 数组按顺序(快指针和慢指针)
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
for j in range(len(nums)):
if(nums[j] != val):
nums[i] = nums[j]
i+=1
return i
② 数组不按顺序(双指针)
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
j = len(nums)
while i < j:
if(nums[i] == val):
nums[i] = nums[j-1]
j -= 1
else:
i += 1
return i