3 loops python code


  • 0
    X
    class Solution(object):
        def threeSum(self, nums):
            nums.sort()
            res = []
            if len(nums) == 3:
                sum = 0
                for i in range(len(nums)):
                    sum += nums[i]
                if sum == 0:
                    res.append(nums)
            elif len(nums) > 3:
                i = 0
                while i < (len(nums) - 2):
                    j = i + 1
                    while j < (len(nums) - 1):
                        two = nums[i] + nums[j]
                        k = j + 1
                        while k < (len(nums)):
                            three = two + nums[k]
                            if three == 0:
                                res.append([nums[i], nums[j], nums[k]])
                            elif three > 0:
                                break
                            if k == len(nums) - 1:
                                k += 1
                            else:
                                while nums[k] == nums[k + 1]:
                                    k += 1
                                    if k == len(nums) - 1:
                                        break
                                k += 1
                        if j == (len(nums) - 2):
                            j += 1
                        else:
                            while nums[j] == nums[j + 1]:
                                j += 1
                                if j == len(nums) - 2:
                                    break
                            j += 1
                    if i == (len(nums) - 3):
                        i += 1
                    else:
                        while nums[i] == nums[i + 1]:
                            i += 1
                            if i == len(nums) - 3:
                                break
                        i += 1
            return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.