Python三數(shù)之和的實現(xiàn)方式
三數(shù)之和題目描述
給你一個包含 n 個整數(shù)的數(shù)組 nums,判斷 nums 中是否存在三個元素 a,b,c ,
使得 a + b + c = 0 ?請你找出所有滿足條件且不重復(fù)的三元組。
答案中不允許包含重復(fù)的三元組。
示例:
給定數(shù)組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[ ? [-1, 0, 1], ? [-1, -1, 2] ]
思路
1. 首先將數(shù)組排序,可以利用Python內(nèi)置函數(shù),也可以利用另外定義排序算法。
2. 應(yīng)用雙指針算法。固定第一個數(shù),索引為i,遍歷整個數(shù)組,第一個數(shù)也是三個數(shù)中最小的數(shù),然后在該數(shù)右面設(shè)置左右兩個指針l和r,l=i+1,r=len(nums)-1,
3. 判斷這三個索引指向的元素和與0的大小關(guān)系。
和>0,右指針左移一位;和<0,左指針右移一位。
由于要避免重復(fù)的三元組,所以移動左右指針的時候要跳過相鄰的所有相等的nums[i]。
Python3代碼
#導入計算時間的包,調(diào)用系統(tǒng)時間 from time import * #初始時間 t1 = time() def threeSum(nums): nums.sort() n = len(nums) res = [] for i in range(n): '''如果相鄰的兩個數(shù)相等,跳過,避免重復(fù)''' if i > 0 and nums[i] == nums[i-1]: continue l, r = i+1, n-1 while l < r: if nums[i] + nums[l] + nums[r]>0: r -= 1 while nums[r+1] == nums[r]: r -= 1 elif nums[i] + nums[l] + nums[r]<0: l += 1 while nums[l-1] == nums[l]: l += 1 else: res.append([nums[i],nums[l],nums[r]]) l += 1 r -= 1 while nums[l] == nums[l - 1]: l += 1 while nums[r] == nums[r + 1]: r -= 1 return res if __name__ == '__main__': nums = [-1,0,1,2,-1,-4] print(threeSum(nums)) #結(jié)束時間 t2 = time() #運行時間 run_time = t2 - t1 print(run_time)
運行結(jié)果:
[[-1, -1, 2], [-1, 0, 1]]
#運行時間
0.0010113716125488281
以上代碼有一些思想錯誤:
遺漏了如果三個數(shù)全部大于0,則退出循環(huán),因為沒有滿足條件的結(jié)果。
沒有嚴格判斷每一次的l<r的條件。
修正后的代碼:
from time import * t1 = time() def threeSum(nums): nums.sort() n = len(nums) res = [] for i in range(n-2): if nums[i] > 0:break '''如果相鄰的兩個數(shù)相等,跳過,避免重復(fù)''' if i > 0 and nums[i] == nums[i-1]: continue l, r = i+1, n-1 while l < r: if nums[i] + nums[l] + nums[r]>0: r -= 1 while l < r and nums[r-1] == nums[r]: r -= 1 elif nums[i] + nums[l] + nums[r]<0: l += 1 while l < r and nums[l] == nums[l-1]: l += 1 else: res.append([nums[i],nums[l],nums[r]]) l += 1 r -= 1 while l < r and nums[l] == nums[l - 1]: l += 1 while l < r and nums[r] == nums[r + 1]: r -= 1 return res if __name__ == '__main__': nums = [-2,-3,0,0,-2] print(threeSum(nums)) t2 = time() run_time = t2 - t1 print(run_time)
結(jié)果:
[]
#時間
0.0
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python實現(xiàn)的生產(chǎn)者、消費者問題完整實例
這篇文章主要介紹了Python實現(xiàn)的生產(chǎn)者、消費者問題,簡單描述了生產(chǎn)者、消費者問題的概念、原理,并結(jié)合完整實例形式分析了Python實現(xiàn)生產(chǎn)者、消費者問題的相關(guān)操作技巧,需要的朋友可以參考下2018-05-05總結(jié)Pyinstaller的坑及終極解決方法(小結(jié))
這篇文章主要介紹了總結(jié)Pyinstaller的坑及終極解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09pandas進行數(shù)據(jù)的交集與并集方式的數(shù)據(jù)合并方法
今天小編就為大家分享一篇pandas進行數(shù)據(jù)的交集與并集方式的數(shù)據(jù)合并方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06Python高階函數(shù)之filter()函數(shù)代碼示例
這篇文章主要介紹了Python高階函數(shù)之filter()函數(shù)代碼示例,獲取了一個序列的時候,想要把一些內(nèi)容去掉,保留一部分內(nèi)容的時候可以使用高效的filter()函數(shù),需要的朋友可以參考下2023-07-07Python打開指定網(wǎng)頁使用requests模塊爬蟲示例詳解
這篇文章主要介紹了Python打開指定網(wǎng)頁使用requests模塊爬蟲的示例,Python?requests是一個常用的HTTP請求庫,可以方便地向網(wǎng)站發(fā)送HTTP請求,并獲取響應(yīng)結(jié)果,requests模塊比urllib模塊更簡潔,感興趣的朋友可以參考下2024-02-02