添加了python代码(数组篇)

为数组篇文件夹下的代码增加了python语言版本
This commit is contained in:
goodyong
2021-07-10 12:20:02 +08:00
parent 4e661354d4
commit 7dd5ce1f3d
13 changed files with 461 additions and 3 deletions

View File

@@ -50,6 +50,8 @@
**题目代码**
Java Code:
```java
class Solution {
public int removeElement(int[] nums, int val) {
@@ -75,6 +77,29 @@ class Solution {
}
```
Python3 Code:
```python
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int)->int:
# 获取数组长度
leng = len(nums)
if 0 == leng:
return 0
i = 0
while i < leng:
# 发现符合条件的情况
if nums[i] == val:
# 前移一位
for j in range(i, leng - 1):
nums[j] = nums[j + 1]
i -= 1
leng -= 1
i += 1
return i
```
**双指针**
快慢指针的做法比较有趣只需要一个 for 循环即可解决时间复杂度为 O(n) ,总体思路就是有两个指针前面一个后面一个前面的用于搜索需要删除的值当遇到需要删除的值时前指针直接跳过后面的指针不动当遇到正常值时两个指针都进行移动并修改慢指针的值最后只需输出慢指针的索引即可
@@ -100,7 +125,7 @@ class Solution {
if (nums[j] == val) {
continue;
}
// 不等于目标值时则赋值给num[i],i++
// 不等于目标值时则赋值给nums[i],i++
nums[i++] = nums[j];
}
return i;