mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2026-03-12 21:01:08 +00:00
添加了python代码(数组篇)
为数组篇文件夹下的代码增加了python语言版本
This commit is contained in:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user