1. 程式人生 > >leetcode 3sum question

leetcode 3sum question

邏輯 while cnblogs app 問題分析 排序 ica 時間復雜度 list()

摘要:

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:

[
  [-1, 0, 1],
  [-1, -1, 2]
]

問題分析:
對數組實現3個值的求和,可以分解為兩個數值的和;問題需要考慮到過濾重復的解決方案和考慮到算法復雜度;
 1 class Solution(object):
 2     def threeSum(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[List[int]]
 6         """
 7         nums.sort() # 根據python的內置列表排序,實現排序
 8         result = list()            
 9         if len(nums) < 3:
10             return result #
判斷,如果輸入列表小於3,直接返回空值 11 for i in range(len(nums) - 2): # 只能遍歷到len(nums)-2,否則越界 12 if i > 0 and nums[i] == nums[i-1]: 13 continue 14 left = i + 1 15 right = len(nums) - 1 16 while left < right: 17 cur_sum = nums[left] + nums[right]
18 target_sum = 0 - nums[i] 19 if cur_sum == target_sum: 20 temp = [nums[i],nums[left],nums[right]] 21 result.append(temp) 22 left +=1 23 right -= 1 24 while left < right and nums[left]==nums[left-1]: 25 left +=1 26 while left < right and nums[right] == nums[right+1]: 27 right -= 1 28 elif cur_sum < target_sum: 29 left += 1 30 else: 31 right -= 1 32 return result

代碼解析:

  第一想法:對數組按照i,j,k三個指針指向進行遍歷,時間復雜度為O(n3),當數組長度很大時,運算速度過慢,造成無法運算

  第二想法:通過搜索查看別人答案,上面的代碼實現時間復雜度為O(nlogn);邏輯為,遍歷一次數組,不重復遍歷。轉化為求2sum的問題



leetcode 3sum question