[leetcode]27. Remove Element删除元素

Given an array nums and a value val, 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.

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.

题意:

给定某个值,要求删除数组中所有等于该值的元素。

思路:

    j 

以[3, 2, 2, 3], value = 3 为例

    i 

指针i遍历数组,遇到非value的值,送到指针j那里去

指针j从0开始,接收所有指针i送来的非value值

扫完一遍后

指针j所指的位置就是新“数组”的长度

代码:

1  public int removeElement(int[] nums, int target) {
2         int index = 0;
3         for (int i = 0; i < nums.length; ++i) {
4             if (nums[i] != target) {
5                 nums[index++] = nums[i];
6             }
7         }
8         return index;
9     }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9125368.html