Skip to content

Instantly share code, notes, and snippets.

@leeliwei930
Last active May 25, 2021 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leeliwei930/69cd95e2cb39d5f063ef5acfdebfd643 to your computer and use it in GitHub Desktop.
Save leeliwei930/69cd95e2cb39d5f063ef5acfdebfd643 to your computer and use it in GitHub Desktop.
Algoexpert Solutions
package main
// [12, 3, 1]
// array distinct, solutions 3 numbers group must be unique
// [3,1,2]
// [1,2,-6]
import ("fmt"
"sort")
func ThreeNumberSum(array []int, target int) [][]int {
solutions := make([][]int,0)
// must be sorted
sort.Ints(array)
for i:=0; i < len(array); i++ {
leftIndex := i + 1 // set left pointer as currentIndex + 1
rightIndex := len(array) - 1 // right pointer as the end of the array
for leftIndex < rightIndex { // continues loop the pointer shifter until the leftIndex pointer passed over rightIndex
currentSum := array[i] + array[leftIndex] + array[rightIndex] // current sum to test all the three sum values
if currentSum > target { // if the currentsum is more than the target
// we need to lower down the value by shifting the right index - 1
rightIndex -= 1
} else if currentSum < target {
// if the currentsum is less than the target
// we need to increase the value by shifting the left index + 1
leftIndex += 1
} else if currentSum == target {
// if we found the currentsum match the target sum, appennd the solution
solutions = append(solutions, []int{ array[i], array[leftIndex], array[rightIndex]})
// then move forward leftIndex, and move the rightIndex backward
leftIndex +=1
rightIndex -=1
}
}
}
fmt.Println(solutions)
return solutions
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment