leetcode python 刷题记录,从易到难
一、题目
二、解答
1.思路
本题和26思路类似。思路就是把所有等于指定数字的元素后移,直到移到最后,最后得到所求数组的索引为[0,最靠前的指定数字的索引 - 1]。
- 创建两个指针指向0,遍历数组,当i指向元素等于指定数字时,i指针后移1位;
- 当i指向元素不等于指定元素时,把i指向的数组赋值给j所在的位置,i和j都后移1位;
- 循环结束后 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