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
更多關于Python相關內容可查看本站專題:《Python字典操作技巧匯總》、《Python字符串操作技巧匯總》、《Python常用遍歷技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
python統(tǒng)計指定目錄內文件的代碼行數(shù)
這篇文章主要介紹了python統(tǒng)計指定目錄內文件的代碼行數(shù)2019-09-09matplotlib之多邊形選區(qū)(PolygonSelector)的使用
這篇文章主要介紹了matplotlib之多邊形選區(qū)(PolygonSelector)的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02Python3編碼問題 Unicode utf-8 bytes互轉方法
今天小編就為大家分享一篇Python3編碼問題 Unicode utf-8 bytes互轉方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10python中數(shù)據(jù)爬蟲requests庫使用方法詳解
本篇文章主要介紹了python中數(shù)據(jù)爬蟲requests庫使用方法詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02