Clear easy to understand Swift solution


  • 0
    A
    class Solution {
        func threeSum(_ nums: [Int]) -> [[Int]] {
            var a = nums.sorted(by: <)
            var result = [[Int]]()
            var idx = 0
            while idx < a.count - 2 {
                let first = a[idx]
                let target = -first
                var low = idx + 1
                var high = a.count - 1
                while low < high {
                    let second = a[low]
                    let third = a[high]
                    if second + third < target {
                        low += 1
                        continue
                    }
                    if second + third > target {
                        high -= 1
                        continue
                    }
                    result.append([first, second, third])
                    while low < a.count - 2 && a[low] == second {
                        low += 1
                    }
                    while high > low && a[high] == third {
                        high -= 1
                    }
                }
                while idx < a.count - 2 && a[idx] == first {
                    idx += 1
                }
            }
            return result
        }
    }
    

Log in to reply
 

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