Skip to content

Commit 4a50469

Browse files
eric496labuladong
authored andcommitted
添加有序数组去重Python3代码
1 parent 2ec69eb commit 4a50469

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

高频面试系列/如何去除有序数组的重复元素.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,48 @@ ListNode deleteDuplicates(ListNode head) {
6666

6767
![labuladong](../pictures/labuladong.png)
6868

69+
[eric wang](https://www.github.com/eric496) 提供有序数组 Python3 代码
70+
71+
```python
72+
def removeDuplicates(self, nums: List[int]) -> int:
73+
n = len(nums)
74+
75+
if n == 0:
76+
return 0
77+
78+
slow, fast = 0, 1
79+
80+
while fast < n:
81+
if nums[fast] != nums[slow]:
82+
slow += 1
83+
nums[slow] = nums[fast]
84+
85+
fast += 1
86+
87+
return slow + 1
88+
```
89+
90+
[eric wang](https://www.github.com/eric496) 提供有序链表 Python3 代码
91+
92+
```python
93+
def deleteDuplicates(self, head: ListNode) -> ListNode:
94+
if not head:
95+
return head
96+
97+
slow, fast = head, head.next
98+
99+
while fast:
100+
if fast.val != slow.val:
101+
slow.next = fast
102+
slow = slow.next
103+
104+
fast = fast.next
105+
106+
# 断开与后面重复元素的连接
107+
slow.next = None
108+
return head
109+
```
110+
69111
[上一篇:如何高效解决接雨水问题](../高频面试系列/接雨水.md)
70112

71113
[下一篇:如何寻找最长回文子串](../高频面试系列/最长回文子串.md)

0 commit comments

Comments
 (0)