I came up with a solution for the 3sum problem on leetcode but even though it passes all test codes it fails because of 'time limit exceeded'.
class Solution(object):
def threeSum(self, nums):
triplet_array = []
x = []
for i in range(len(nums)):
for j in range(i+1, len(nums)):
for k in range(j+1, len(nums)):
if nums[i] + nums[j] + nums[k] == 0:
if i !=j and i !=k and j != k:
if [nums[i], nums[j], nums[k]] != x:
x = [nums[i], nums[j], nums[k]]
x.sort()
if x not in triplet_array:
triplet_array.append(x)
return triplet_array
I don't know how to perform the 'space/time' analysis that it keeps referencing so I'm wondering how I go about making this solution more efficient so that it will pass all test cases in the allotted time.
For reference the 3sum problem details can be found here: https://leetcode.com/problems/3sum/
One tip would be to sort the incoming array first. If you know that three elements at indices i, j, and k add up to more than 0, then increasing i, j, or k (so long as the list is sorted) will also be more than 0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.