27.leetcode 移除元素(简单)

leetcode python 刷题记录,从易到难

一、题目

在这里插入图片描述
在这里插入图片描述

二、解答

1.思路

本题和26思路类似。思路就是把所有等于指定数字的元素后移,直到移到最后,最后得到所求数组的索引为[0,最靠前的指定数字的索引 - 1]。

  1. 创建两个指针指向0,遍历数组,当i指向元素等于指定数字时,i指针后移1位;
  2. 当i指向元素不等于指定元素时,把i指向的数组赋值给j所在的位置,i和j都后移1位;
  3. 循环结束后 j 就是所求数组的长度;

2.实现

class Solution:

    # execute time out
    def removeElement(self, nums, val):
        if not nums:
            return 0
        i = 0
        j = 0
        while i < len(nums):
            if nums[i] == val:
                i = i + 1
            else:
                nums[j] = nums[i]
                i = i + 1
                j = j + 1
        return j

3.提交

在这里插入图片描述

Github地址

https://github.com/m769963249/leetcode_python_solution/blob/master/easy/27.py

参考连接

https://leetcode-cn.com/

猜你喜欢

转载自blog.csdn.net/qq_39945938/article/details/108068675