Fork me on GitHub

LeetCode 第27题--移除元素

 

1. 题目

2.题目分析与思路

3.代码

 

1. 题目

给定 nums = [3,2,2,3], val = 3,

函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。

你不需要考虑数组中超出新长度后面的元素。

2. 思路

  这道题经典的双指针,或者使用很奇特的做法,用python的后续遍历

3. 代码

   双指针

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        count = len(nums) -1 
        i = 0
        if len(nums) == 0:
            return 0
        while(i < count):
            if nums[count] == val:
                count -= 1
                continue
            if nums[i] == val:
                nums[i],nums[count] = nums[count],nums[i]
                i += 1
                count -= 1
            else:
                i += 1
        if nums[i] == val:
            return i
        else:
            return i+1

python 后续遍历:

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        j=len(nums)
        for i in range(j-1,-1,-1):
            if nums[i]==val:
                nums.pop(i)    
        return len(nums)        

那为什么不能用前向遍历呢,因为使用pop会改变数组长度,pop完后指针又自增1,就会导致漏掉数字,感觉挺有意思的这个解法。

posted @ 2019-10-09 10:16  顾鹏pen  阅读(164)  评论(0编辑  收藏  举报