18 4sum

·data-structure-and-algorithm
#hash-table

15. 三数之和

go:

import "sort"

func fourSum(nums []int, target int) [][]int {
    sort.Ints(nums)

    var results [][]int
    length := len(nums)

    if length < 4 {
        return results
    }

    for i := 0; i < length - 3; i++ {
        if i > 0 && nums[i] == nums[i - 1] {
            continue
        }

        for j := i + 1; j < length - 2; j++ {
            if j > i + 1 && nums[j] == nums[j - 1] {
                continue
            }

            left, right := j + 1, length - 1
            remain := target - nums[i] - nums[j]
            
            for left < right {
                sum := nums[left] + nums[right]
                
                if sum < remain {
                    left++
                } else if sum > remain {
                    right--
                } else {
                    results = append(results, []int{nums[i], nums[j], nums[left], nums[right]})

                    for left < right && nums[left] == nums[left + 1] {
                        left++
                    }

                    for left < right && nums[right] == nums[right - 1] {
                        right--
                    }

                    left++
                    right--
                }
            }
        }
    }

    return results
}