美文网首页
15.三数之和

15.三数之和

作者: 寂灭天骄小童鞋 | 来源:发表于2020-03-06 14:45 被阅读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
}

相关文章

网友评论

      本文标题:15.三数之和

      本文链接:https://www.haomeiwen.com/subject/efeirhtx.html