def threeSum(nums): nums.sort() result = [] n = len(nums) for i in range(n): if i > 0…
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
def threeSum(nums): nums.sort() result = [] n = len(nums)
codefor i in range(n): if i > 0 and nums[i] == nums[i - 1]: continue # Pular duplicatas para o índice i left, right = i + 1, n - 1 while left < right: total = nums[i] + nums[left] + nums[right] if total == 0: result.append([nums[i], nums[left], nums[right]]) left += 1 right -= 1 # Pular duplicatas para o ponteiro left while left < right and nums[left] == nums[left - 1]: left += 1 # Pular duplicatas para o ponteiro right while left < right and nums[right] == nums[right + 1]: right -= 1 elif total < 0: left += 1 else: right -= 1 return resultExemplos de uso:
print(threeSum([-1, 0, 1, 2, -1, -4])) # Output: [[-1, -1, 2], [-1, 0, 1]] print(threeSum([0, 1, 1])) # Output: [] print(threeSum([0, 0, 0])) # Output: [[0, 0, 0]]
Assistant
The function you provided is an implementation of the 3Sum problem, which aims to find all unique triplets in the array which gives the sum of zero.
Here's a brief explanation of how it works:
- First, we sort the list of numbers to make it easier to avoid duplicates and to navigate through the list.
- We then iterate over each number in the list. If the current number is equal to the previous one (indicating a duplicate), we skip it to ensure uniqueness in our results.
- For each number, we set two pointers,
leftandright, initially at positions immediately after the current number and at the end of the list respectively. - We then enter a loop where we check the sum of the current number and the numbers pointed by
leftandright. If this sum equals zero, we append these three numbers as a triplet to our result list and move both pointers towards the center. - If the sum is less than zero, we increment
leftpointer (as we need a larger number to balance out the sum). If the sum is greater than zero, we decrement pointer (as we need a smaller number).