Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such…
- User
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Assistant
Sure, I can help you with that. The problem you're describing is a variation of the classic "three sum" problem. Here's a Python solution using a two-pointer approach:
pythonclass Solution: def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() res = [] for i in range(len(nums)-2): if i > 0 and nums[i] == nums[i-1]: continue left, right = i+1, len(nums)-1 while left < right: total = nums[i] + nums[left] + nums[right] if total < 0: left += 1 elif total > 0: right -= 1 else: res.append([nums[i], nums[left], nums[right]]) while left < right and nums[left] == nums[left+1]: left += 1 while left < right and nums[right] == nums[right-1]: right -= 1 left += 1 right -= 1 return res- User
Please, write this for me in rust
Assistant
Sure, here's a Rust solution for the three sum problem:
rust