1. 程式人生 > >Python 3 LeetCode三數之和

Python 3 LeetCode三數之和

# -*- coding :UTF-8 -*-

class Solution:
    def threeSum(self, nums):
        result = []
        temp_nums = sorted(nums)
        l = len(temp_nums)
        for i in range(l - 2):
            if i > 0 and temp_nums[i] == temp_nums[i -1]:
                continue
            else:
                if temp_nums[i] <= 0:#只迴圈負數
                    j = i + 1
                    k = l - 1
                    while j < k:
                        x = temp_nums[i] + temp_nums[j] + temp_nums[k]
                        if x == 0:
                            while j < k and temp_nums[j] == temp_nums[j+1]:#去掉重複部分左邊
                                j += 1
                            while j < k and temp_nums[k] == temp_nums[k-1]:#去掉重複部分右邊
                                k -= 1
                            result.append((temp_nums[i], temp_nums[j], temp_nums[k]))
                            j += 1
                        elif x > 0:
                            k -= 1
                        else:
                            j += 1
                else:
                    break
        return result