程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python leetcode_ 26. delete duplicates in an ordered array

編輯:Python

subject :

"""
Here's an ordered array nums , Please delete the repeated elements in place , Make each element appear only once , Returns the new length of the deleted array .
Don't use extra array space , You have to modify the input array in place And using O(1) Complete with extra space .
"""

Law 1 : Remove duplicate elements from the original array

class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
i = 0
while i < len(nums):
if len(nums)==1:
break
if nums[i]==nums[i-1]:# Remove duplicate elements from the original array
del nums[i]
else:
i += 1
return len(nums)

Law two : Double pointer

fast The pointer is used to scan ,slow The pointer is used to point to the position of the answer 
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
n = len(nums)
fast = slow = 1 #fast The pointer is used to scan ,slow The pointer is used to point to the position of the answer
while fast < n:
if nums[fast] != nums[fast - 1]: # When no duplicates are found , take fast Copy location to slow
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
nums = [0,0,1,1,2]
S = Solution()
result = S.removeDuplicates(nums)
print(result)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved