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.
思路:遍历数组,后边往前放。
public class Solution {
public int removeElement(int[] nums, int val) {
int newIndex = 0;
for (int oldIndex = 0; oldIndex < nums.length; ++oldIndex) {
if (nums[oldIndex] != val) {
nums[newIndex++] = nums[oldIndex];
}
}
return newIndex;
}
}

本文介绍了一种在数组中移除特定值并返回新长度的算法实现。通过遍历数组并将不等于目标值的元素向前移动,该算法能有效地完成元素的移除,并允许元素顺序发生变化。

被折叠的 条评论
为什么被折叠?



