Python實現(xiàn)刪除排序數(shù)組中重復項的兩種方法示例
本文實例講述了Python實現(xiàn)刪除排序數(shù)組中重復項的兩種方法。分享給大家供大家參考,具體如下:
對于給定的有序數(shù)組nums,移除數(shù)組中存在的重復數(shù)字,確保每個數(shù)字只出現(xiàn)一次并返回新數(shù)組的長度
注意:不能為新數(shù)組申請額外的空間,只允許申請O(1)的額外空間修改輸入數(shù)組
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
說明:為什么返回列表長度而不用返回列表?因為列表傳入函數(shù)是以引用的方式傳遞的,函數(shù)中對列表進行的修改會被保留。
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
1. 簡單判斷列表中元素是否相等,相等就刪除多余元素
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
if len(nums)==1: #單獨判斷列表長度為1的情況,因為之后的for循環(huán)從下標1開始
return 1
temp_num = nums[0]
count =0 #for循環(huán)中動態(tài)刪除列表元素,列表縮短,為了防止下標溢出需要用count標記刪除元素個數(shù)
for index, num in enumerate(nums[1:]):
if temp_num == num: #元素相等就刪除
del nums[index-count]
count += 1
else:
temp_num = num
return len(nums)
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
forth = 0
back = 1
while back <= len(nums)-1:
if nums[forth] == nums[back]:
nums.pop(back)
else:
forth += 1
back += 1
return len(nums)
2. 修改數(shù)組,保證數(shù)組的前幾個數(shù)字互不相同,且這幾個數(shù)字的長度同返回長度相等
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
length = 0 #不存在重復數(shù)字的數(shù)組長度
for index in range(1,len(nums)): #遍歷數(shù)組
if nums[index] != nums[length]:
length += 1
nums[length] = nums[index]
return length+1
算法題來自:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/description/
PS:本站還有兩款比較簡單實用的在線文本去重復工具,推薦給大家使用:
在線去除重復項工具:
http://tools.jb51.net/code/quchong
在線文本去重復工具:
http://tools.jb51.net/aideddesign/txt_quchong
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python字典操作技巧匯總》、《Python字符串操作技巧匯總》、《Python常用遍歷技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python編寫的com組件發(fā)生R6034錯誤的原因與解決辦法
pythoncom27.dll可能沒有包含manifest信息,或者沒有包含正確的manifest信息,或者系統(tǒng)中的c++ runtime library受到破壞都有可能造成這種現(xiàn)象2013-04-04
Pytorch中Softmax和LogSoftmax的使用詳解
這篇文章主要介紹了Pytorch中Softmax和LogSoftmax的使用詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

