This is a Leetcode problem -
Given an array
nums
ofn
integers, are there elements \$a, b, c\$ innums
such that \$a + b + c\$ =0
? Find all unique triplets in the array which gives the sum of zero.Note -
The solution set must not contain duplicate triplets.
Example -
Given array
nums
=[-1, 0, 1, 2, -1, -4]
,A solution set is -
[ [-1, 0, 1], [-1, -1, 2] ]
NOTE -
[-1, 0, 1]
and[1, 0, -1]
are considered duplicates.
Here is my solution to this challenge -
def three_sum(nums):
if nums == None or len(nums) < 3:
return []
res = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
j = i + 1
k = len(nums) - 1
while j < k:
if nums[i] + nums[j] + nums[k] > 0:
k -= 1
while nums[k] == nums[k + 1] and k > j:
k -= 1
elif nums[i] + nums[j] + nums[k] < 0:
j += 1
while nums[j] == nums[j - 1] and j < k:
j += 1
else:
res.append([nums[i], nums[j], nums[k]])
j += 1; k -= 1
while nums[k] == nums[k + 1] and k > j:
k -= 1
while nums[j] == nums[j - 1] and j < k:
j += 1
return res
So I would like to know whether I could make my program shorter and more efficient. Also, I would like to know if I could make my code PEP 8 compliant (if possible) as I'm having trouble (understanding) with the PEP 8 checker (I need explanations for why I'm getting these errors) -
Also, any recommendations for better PEP 8 checkers? I'll be glad to know.