golang solution o(N^2)


  • 0
    G
    func threeSum(nums []int) [][]int {
        sort.Ints(nums)
        var res [][]int
        for i := 0; i < len(nums) - 2; i++ {
            
            if i > 0 && nums[i] == nums[i - 1]{
                continue
            }
            
            for j,k := i + 1,len(nums) - 1; j < k;{
                
                if j > i + 1 && nums[j] == nums[j - 1] {
                    j++
                    continue
                }
                
                if k < len(nums) - 1 && nums[k] == nums[k + 1]{
                    k--
                    continue
                }
           
                switch sum := nums[i] + nums[j] + nums[k];{
                    case sum == 0:
                        v := []int{nums[i],nums[j],nums[k]}
                        res = append(res,v)
                        j++ 
                        k--
                    case sum < 0:
                        j++
                    default:
                        k--;
                }
            }
        }
        return res
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.