feat(15-3sum): add golang solution

This commit is contained in:
Sangeeth Sudheer 2022-02-28 06:27:17 +05:30
parent 63397e07cd
commit 3fed6cd2f9
2 changed files with 69 additions and 0 deletions

20
015_3sum/README.md Normal file
View File

@ -0,0 +1,20 @@
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`.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = [] Output: []
Example 3:
Input: nums = [0] Output: []
Constraints:
* `0 <= nums.length <= 3000`
* `-105 <= nums[i] <= 105`

View File

@ -0,0 +1,49 @@
func threeSum(nums []int) (result [][]int) {
target := 0
sort.Ints(nums)
for i := 0; i < len(nums)-2; i++ {
// We don't want duplicates of the fixed value
// which can cause duplicate triplets to appear.
if i > 0 && nums[i] == nums[i-1] {
continue
}
startPtr := i + 1
endPtr := len(nums) - 1
for startPtr < endPtr {
sum := nums[i] + nums[startPtr] + nums[endPtr]
if sum == target {
result = append(
result,
[]int{nums[i], nums[startPtr], nums[endPtr]},
)
// Duplicate values can appear while scanning also. Presence of these
// duplicate values can also result in duplicate triplets. So, for the
// start and end pointers, we need to keep moving them until we are
// clear of duplicates.
for startPtr < endPtr && nums[startPtr] == nums[startPtr+1] {
startPtr++
}
for endPtr > startPtr && nums[endPtr] == nums[endPtr-1] {
endPtr--
}
// Since the loops above stop at the last duplicate value, we need to move
// them by one step from both directions to continue with the logic.
startPtr++
endPtr--
} else if sum < target {
startPtr++
} else {
endPtr--
}
}
}
return
}