• [LeetCode] 27. 移除元素


    题目链接: https://leetcode-cn.com/problems/remove-element/

    题目描述:

    给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。

    不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

    元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

    示例:

    示例 1:

    给定 nums = [3,2,2,3], val = 3,
    
    函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。
    
    你不需要考虑数组中超出新长度后面的元素。
    

    示例 2:

    给定 nums = [0,1,2,2,3,0,4,2], val = 2,
    
    函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。
    
    注意这五个元素可为任意顺序。
    
    你不需要考虑数组中超出新长度后面的元素。
    

    思路:

    思路1:

    用双指针,一个从头向后扫,一个从尾向前扫,头指针把等于val和尾指针不等于val调换即可.

    时间复杂度:(O(n))

    思路2:

    依次把不等于val往前移,

    题目中没说不可以改变原来的数组的数值,所以,可以交换,也可以覆盖!

    时间复杂度:(O(n))


    关注我的知乎专栏,了解更多的解题技巧,大家共同进步!

    代码:

    思路1:

    class Solution:
        def removeElement(self, nums: List[int], val: int) -> int:
            if not nums:return 0
            slow = 0   
            n = len(nums)
            fast = n - 1
            while slow < fast:
                while slow < fast and nums[slow] != val:
                    slow += 1
                while slow < fast and nums[fast] == val:
                    fast -= 1
                nums[slow],nums[fast] = nums[fast],nums[slow]
                slow += 1
                fast -= 1
            res = 0
            #print(nums,slow,fast)
            #return fast + 1
            for i in range(n):
                if nums[i] == val:
                    return res
                res += 1
    

    思路2:

    覆盖(python)

    class Solution:
        def removeElement(self, nums: List[int], val: int) -> int:
            idx = 0
            for i in range(len(nums)):
                if nums[i] != val:
                    nums[idx] = nums[i]
                    idx += 1
            return idx
    

    java

    class Solution {
        public int removeElement(int[] nums, int val) {
            int n = nums.length;
            int index = 0;
            for (int i = 0; i < n; i++){
                if (nums[i] != val) nums[index++] = nums[i];
            }
            return index;
        }
    }
    

    交换

    class Solution:
        def removeElement(self, nums: List[int], val: int) -> int:
            idx = 0
            for i in range(len(nums)):
                if nums[i] != val:
                    nums[idx],nums[i] = nums[i],nums[idx]
                    idx += 1
            #print(nums)
            return idx
    
  • 相关阅读:
    mysql的四种隔离
    mysql-事物
    Mysql数据备份
    线程池
    springboot整合log4j2
    springboot项目部署
    数组去重
    倒叙输出算法
    使用LLDB和debugserver对ios程序进行调试
    Linux使用pyinstaller 编译py成可执行程序
  • 原文地址:https://www.cnblogs.com/powercai/p/10797009.html
Copyright © 2020-2023  润新知