Skip to content

Latest commit

 

History

History
45 lines (42 loc) · 1019 Bytes

林浩特-20180901.md

File metadata and controls

45 lines (42 loc) · 1019 Bytes

【leetcode 算法题】

https://leetcode.com/problems/3sum/description/

func threeSum(nums []int) [][]int {
    if len(nums) < 3 {
        return [][]int{}
    }
    if !sort.IntsAreSorted(nums) {
        sort.Ints(nums)
    }
    result := [][]int{}
    for i:=0; i<len(nums)-2; i++ {
        if i > 0 && nums[i] == nums[i-1] {
            continue
        }
        a := nums[i]
        sumBC := 0 - a
        lo := i+1
        hi := len(nums)-1
        for lo < hi {
            b := nums[lo]
            c := nums[hi]
            if b + c < sumBC {
                lo++
            } else if b + c > sumBC {
                hi--
            } else {
                result = append(result, []int{a, b, c})
                for ;lo < hi && nums[lo] == nums[lo+1]; {
                    lo++
                }
                for ;lo < hi && nums[hi] == nums[hi-1]; {
                    hi--
                }
                lo++
                hi--
            }
        }
    }
    return result
}