4 sum
問題:給定一個數組和一個目標值,輸出數組中所有的4個數之和為目標值的可能組合
解決思路:先排序,再固定其中兩個值,對另外兩個值進行遍歷
class Solution(object):def fourSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[List[int]]"""length = len(nums)if length < 4:return []out = []nums.sort()for i in range(length-3):if i > 0 and nums[i] == nums[i-1]:continuefor j in range(i+1,length-2):if j > i+1 and nums[j] == nums[j-1]:continueexpect_two_sum = target-nums[i]-nums[j]l = j+1r = length-1while l < r:two_sum = nums[l] + nums[r]if two_sum > expect_two_sum or (r < length-1 and nums[r]==nums[r+1]):r -= 1elif two_sum < expect_two_sum or (l > j + 1 and nums[l] == nums[l-1]):l += 1else:out.append([nums[i],nums[j],nums[l],nums[r]])l += 1r -= 1return out?
轉載于:https://www.cnblogs.com/wenqinchao/p/10593119.html
總結
- 上一篇: 关于对接保税仓物流系统或支付系统推送报关
- 下一篇: 比较版本号