LeetCode 27 移除元素

题目描述

给定一个数列nums和数值val,消除数列nums中与数值 val相同的元素,最终返回新数列的长度;要求:不能开辟空间分配新的数列,必须改变原输入nums数列;并对修改后的nums数列的元素顺序没有要求,可以被修改。

Examples

  1. nums=[3,2,2,3val=3 则返回长度为2;
  2. nums=[0,1,2,2,3,0,4,2]val=2则返回长度为5;

其实这道题目与#26消除重复元素差不多,本题指定了消除的元素;不同点在于:首先要判断val是否一定在nums内,这一点与消除重复元素不同——一定在其中。

参考实现

方式1

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        if val not in nums:
            #如果不存在指定元素,直接返回数组长度
            return len(nums)
        else:
            i = 0
            while i < len(nums):
                #找到指定元素
                if val == nums[i]:
                    #移除指定元素
                    nums.pop(i)
                else:
                    #循环条件 + 1
                    i += 1
            return i

方式2

def removeElement_02(nums: List[int], val: int):
    nums[:] = [n for n in nums if n != val]
    return len(nums)

这里借助推导式实现,简洁多看两遍也能理解;

Java 版本

双指针解法

    public static int removeElement01(int[] nums, int val) {
        //声明左右指针
        int left = 0, right = nums.length - 1;
        while (left < right) {
            if (nums[left] == val) {
                nums[left] = nums[right--];
            } else {
                left++;
            }
        }
        return left;
    }

通用解法

    public static int removeElement(int[] nums, int val) {
        int index = 0;
        for (int num : nums) {
            if (num != val) {
                nums[index++] = num;
            }
        }
        return index;
    }
posted @ 2023-07-02 09:32  晓枫的春天  阅读(23)  评论(0编辑  收藏  举报