mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
feat:修改 27 题 python 代码格式错误问题并增加快慢指针的解法
This commit is contained in:
@ -77,7 +77,7 @@ public:
|
||||
|
||||
双指针法(快慢指针法): **通过一个快指针和慢指针在一个for循环下完成两个for循环的工作。**
|
||||
|
||||
定义快慢指针
|
||||
定义快慢指针
|
||||
|
||||
* 快指针:寻找新数组的元素 ,新数组就是不含有目标元素的数组
|
||||
* 慢指针:指向更新 新数组下标的位置
|
||||
@ -196,26 +196,44 @@ class Solution {
|
||||
|
||||
Python:
|
||||
|
||||
```python3
|
||||
```python 3
|
||||
class Solution:
|
||||
def removeElement(self, nums: List[int], val: int) -> int:
|
||||
if nums is None or len(nums)==0:
|
||||
return 0
|
||||
if nums is None or len(nums)==0:
|
||||
return 0
|
||||
l=0
|
||||
r=len(nums)-1
|
||||
while l<r:
|
||||
while l<r:
|
||||
while(l<r and nums[l]!=val):
|
||||
l+=1
|
||||
while(l<r and nums[r]==val):
|
||||
r-=1
|
||||
nums[l], nums[r]=nums[r], nums[l]
|
||||
print(nums)
|
||||
if nums[l]==val:
|
||||
return l
|
||||
else:
|
||||
if nums[l]==val:
|
||||
return l
|
||||
else:
|
||||
return l+1
|
||||
```
|
||||
|
||||
``` python 3
|
||||
class Solution:
|
||||
def removeElement(self, nums: List[int], val: int) -> int:
|
||||
# 快慢指针
|
||||
fast = 0 # 快指针
|
||||
slow = 0 # 慢指针
|
||||
size = len(nums)
|
||||
while fast < size: # 不加等于是因为,a = size 时,nums[a] 会越界
|
||||
# slow 用来收集不等于 val 的值,如果 fast 对应值不等于 val,则把它与 slow 替换
|
||||
if nums[fast] != val:
|
||||
nums[slow] = nums[fast]
|
||||
slow += 1
|
||||
fast += 1
|
||||
return slow
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
Go:
|
||||
```go
|
||||
@ -268,7 +286,7 @@ Ruby:
|
||||
```ruby
|
||||
def remove_element(nums, val)
|
||||
i = 0
|
||||
nums.each_index do |j|
|
||||
nums.each_index do |j|
|
||||
if nums[j] != val
|
||||
nums[i] = nums[j]
|
||||
i+=1
|
||||
@ -342,7 +360,7 @@ int removeElement(int* nums, int numsSize, int val){
|
||||
if(nums[fast] != val) {
|
||||
//将其挪到慢指针指向的位置,慢指针+1
|
||||
nums[slow++] = nums[fast];
|
||||
}
|
||||
}
|
||||
}
|
||||
//最后慢指针的大小就是新的数组的大小
|
||||
return slow;
|
||||
|
Reference in New Issue
Block a user