【LeetCode 15. 3Sum】

Description

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

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

思路

題目要求找出所有三個和爲 0 的元素構成的非重複三元數組。首先對數組進行一個排序,排序後循環先取一個數固定,用雙指針分別指向當前元素的下一個和數組尾數,判斷三者的和與 0 的大小來移動兩個指針,並進行去重。

Kotlin代碼實現

 fun threeSum(nums: IntArray): List<List<Int>> {
    val answer: ArrayList<List<Int>> = ArrayList()
    val length = nums.size
    if (length < 3) return answer
    Arrays.sort(nums)
    for (i in 0 until length) {
        if (nums[i] > 0) break

        if (i > 0 && nums[i] == nums[i - 1]) continue

        var left = i + 1
        var right = length - 1
        while (left < right) {
            val sum = nums[i] + nums[left] + nums[right]
            if (sum == 0) {
                answer.add(listOf(nums[i], nums[left], nums[right]))

                while (left < right && nums[left] == nums[left + 1]) left++
                while (left < right && nums[right] == nums[right - 1]) right--
                left++
                right--
            } else if (sum < 0){
                left++
            } else if (sum > 0){
                right--
            }
        }
    }
    return answer
}

參考:
https://leetcode.com/problems/3sum/solution/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章