Python solution using bi-search


  • 0
    C

    class Solution(object):

    def threeSum(self, num):
        list = []
        orderedNum = sorted(num)
        for i in range(0,len(num)-2):
            if(i==0 or (i>0 and orderedNum[i]!=orderedNum[i-1])):
                low = i+1
                high = len(num)-1
                sum = 0-orderedNum[i]
                while (low < high):
                    if orderedNum[low] + orderedNum[high] == sum:
                        list.append([orderedNum[i],orderedNum[low],orderedNum[high]])
                        while(low < high and orderedNum[low]==orderedNum[low+1]):
                            low = low + 1
                        while (low < high and orderedNum[high]==orderedNum[high-1]):
                            high = high -1
                        low = low + 1
                        high = high -1
                    elif orderedNum[low] + orderedNum[high] < sum:
                        low = low +1
                    else:
                        high = high -1
        return list

  • 0
    S

    Your code doesn't work. Why don't you even try to run it first.


Log in to reply
 

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