美文网首页
Swift ~ 三数之和

Swift ~ 三数之和

作者: 派大星的博客 | 来源:发表于2019-02-15 16:59 被阅读0次

leetcode.三数之和

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.

For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)

具体解题实现

  • 对数组进行排序
  • 转换为双指针问题,left--> <--right
来自网络盗图,数组应该已排序.png
func threeSum(_ nums: [Int]) -> [[Int]] {
    if nums.count < 3 { return [] }
    var nums = nums.sorted()
    let target = 0
    var result : [[Int]] = []
    for a in 0 ..< nums.count - 2 {
        // 转换为双指针(b 、 c)问题
        var b = a + 1
        var c = nums.count - 1
        
        // 剪枝,避免不必要的循环
        if (nums[a] > target) {break}
        if (nums[a] + nums[a + 1] + nums[a + 2] > target) { break }
        if (a > 0 && nums[a] == nums [a - 1]) { continue }
        if (nums[a] + nums[c] + nums[c - 1] < target) { continue }
        
        //  双指针左右逼进
        while (b < c) {
            let sum = nums[a] + nums[b] + nums[c]
            if sum > target {
                c -= 1
                while (b < c && nums[c] == nums [c + 1]) { c -= 1 }
            }
            // 符合条件的三元组输出
            else if sum == target {
                result.append([nums[a], nums[b] , nums[c]])
                b += 1
                c -= 1
                while (b < c && nums[c] == nums [c + 1]) { c -= 1 }
                while (b < c && nums[b] == nums [b - 1]) { b += 1 }
            }
                
            else {
                b += 1
                while (b < c && nums[b] == nums [b - 1]) { b += 1 }
            }
        }
    }
    return result
}

相关文章

  • Swift ~ 三数之和

    leetcode.三数之和 Given an array S of n integers, are there e...

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

  • Swift刷算法:三数之和

    给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + ...

  • [算法]第 3 天 双指针

    283. 移动零 题解 Swift 167. 两数之和 II - 输入有序数组 题解 Swift Git[http...

  • IOS 算法合集

    这里用来总结记录所有算法(大部分Swift) 中级篇IOS 算法(中级篇) ----- 三数之和求解问题[http...

  • 解决两数之和 (Javascript, Java, C#, Sw

    解决两数之和(Javascript, Java, C#, Swift, Kotlin, Python,C++,Go...

  • 两数之和 swift

    题目来源 leetCode题目描述给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目...

  • 两数之和 Swift

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

  • LeetCode 第18题:四数之和

    1、前言 2、思路 采用三数之和的思路,原本三数之和可以分解为:数组中的一个数 + 此数右边的数求两数之和,那么四...

  • 两数之和&三数之和&四数之和&K数之和

    今天看了一道谷歌K数之和的算法题,忽然想起来之前在力扣上做过2、3、4数之和的题,觉得很有必要来整理一下。其实2、...

网友评论

      本文标题:Swift ~ 三数之和

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