Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1759 from a0bb/master
Browse files Browse the repository at this point in the history
修改 27 题 python 代码格式错误问题并增加快慢指针的解法
  • Loading branch information
youngyangyang04 committed Dec 1, 2022
2 parents 6813937 + eeeb64d commit 39ecb52
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions problems/0027.移除元素.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public:

双指针法(快慢指针法): **通过一个快指针和慢指针在一个for循环下完成两个for循环的工作。**

定义快慢指针
定义快慢指针

* 快指针:寻找新数组的元素 ,新数组就是不含有目标元素的数组
* 慢指针:指向更新 新数组下标的位置
Expand Down Expand Up @@ -196,21 +196,26 @@ class Solution {

Python:

```python3

``` python 3
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
# 快指针遍历元素
fast = 0
# 慢指针记录位置
slow = 0
for fast in range(len(nums)):
# 快慢指针
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
func removeElement(nums []int, val int) int {
Expand Down Expand Up @@ -262,7 +267,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
Expand Down Expand Up @@ -336,7 +341,7 @@ int removeElement(int* nums, int numsSize, int val){
if(nums[fast] != val) {
//将其挪到慢指针指向的位置,慢指针+1
nums[slow++] = nums[fast];
}
}
}
//最后慢指针的大小就是新的数组的大小
return slow;
Expand Down

0 comments on commit 39ecb52

Please sign in to comment.