15.三数之和

2020-03-06  本文已影响0人  寂灭天骄小童鞋

https://leetcode-cn.com/problems/3sum/

func threeSum(_ nums: [Int]) -> [[Int]] {
    var result = [[Int]]()
    if nums.count < 3  {return result}
    let sortedArr = nums.sorted()
    for (idx, value) in sortedArr.enumerated() {
        if value > 0 {break}
        //去重
        if idx > 0 && value == sortedArr[sortedArr.index(sortedArr.startIndex, offsetBy: idx - 1)] {continue}
        var L = idx + 1
        var R = sortedArr.count - 1
        while L < R {
            let leftValue = sortedArr[sortedArr.index(sortedArr.startIndex, offsetBy: L)]
            let rightValue = sortedArr[sortedArr.index(sortedArr.startIndex, offsetBy: R)]
            let sum = value + leftValue + rightValue
            if sum == 0 {
                result.append([value, leftValue, rightValue])
                //右侧左右界限去重
                while L < R && (sortedArr[sortedArr.index(sortedArr.startIndex, offsetBy: L)] == sortedArr[sortedArr.index(sortedArr.startIndex, offsetBy: L + 1)]) {
                    L = L + 1
                }
                while L < R && (sortedArr[sortedArr.index(sortedArr.startIndex, offsetBy: R)] == sortedArr[sortedArr.index(sortedArr.startIndex, offsetBy: R - 1)]) {
                    R = R - 1
                }
                L = L + 1
                R = R - 1
            } else if sum > 0 {
                R = R - 1
            } else if sum < 0 {
                L = L + 1
            }
        }
    }
    return result
}

上一篇 下一篇

猜你喜欢

热点阅读