LeetCode题解7:移除元素

题目

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.

Example 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.

Example 2:

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.

题目要求

  1. 给定一个数组和一个值,去除这个数组中的所有给定的值
  2. 不能开辟新的内容,只能在给定的数组上进行更改
  3. 返回去除元素后的数组的长度

解题思路

采用双指针法:维护一个指向头部、一个指向尾部的指针以及数组长度。从头到尾移动头部指针遍历数组,如果遇到要移除的值,则查看尾部的指针,如果尾部指针指向的不是要移除的值,交换头尾指针指向的值;如果是直接移动指针移除这个值,然后更新数组长度和尾指针。重复这一个过程

时间复杂度O(n),超过100%的java提交,代码如下:

class Solution {
    public int removeElement(int[] nums, int val) {
        int len = nums.length;
        int pointer = len-1;
        for(int i = 0;i < len;i++){
            if(nums[i]==val){
                while(len > 0&&nums[pointer]==val) {
                    len--;
                    pointer--;
                }
                if(len == 0) return 0;
                if(i < pointer){ // 只有头尾没有相遇的时候交换
                    nums[i] = nums[pointer];
                    len--;
                    pointer--;
                }
                
            }
        }
        return len;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_37994110/article/details/88084362