经典算法面试题系列 (二)——three sum
2017-06-15 15:44
323 查看
接着two sum,three sum的难度上升了不少。因为two sum的答案是唯一的,three sum的答案是多个。题目链接https://leetcode.com/problems/3sum/#/description。
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: The solution set must not contain duplicate triplets.
1.golang 版
2.php 版
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: 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] ]其实还是像two sum,先假设已经找到第一个数,剩下的就是循环判断第二个数加上第三个数等于第一个数。当然还有一个问题,就是需要处理重复。处理重复思路是这样的,先找到所有的组合,再做处理。
1.golang 版
package main import ( "fmt" "sort" ) func main() { var nums = []int{-1, 0, 1, 2, -1, -4} three := threeSum(nums) fmt.Println(three) } func threeSum(nums []int) [][]int { if len(nums) <= 0 { return [][]int{} } if !sort.IntsAreSorted(nums) { sort.Ints(nums) } var sum int var res [][]int for i := 0; i < len(nums); i++ { target := -nums[i] front := i + 1 back := len(nums) - 1 for front < back { sum = nums[front] + nums[back] if sum < target { front++ } else if sum > target { back-- } else { var tripliet = []int{nums[i], nums[front], nums[back]} res = append(res, tripliet) for front < back && nums[front] == tripliet[1] { front++ } for front < back && nums[back] == tripliet[2] { back-- } } } for i+1 < len(nums) && nums[i+1] == nums[i] { i++ } } return res }
2.php 版
function threeSum($nums) { if (count($nums) <= 0) { return [[]]; } sort($nums); $res = []; for($i = 0; $i < count($nums); $i++) { $target = -$nums[$i]; $front = $i + 1; $back = count($nums) - 1; while($front < $back) { $sum = $nums[$front] + $nums[$back]; if ($sum < $target) { $front ++; } else if ($sum > $target) { $back --; } else { $triplet = [$nums[$i], $nums[$front], $nums[$back]]; $res[] = $triplet; while($front < $back && $nums[$front] == $triplet[1]) { $front ++; } while($front < $back && $nums[$back] == $triplet[2]) { $back --; } } } while($i + 1 < count($nums) && $nums[$i + 1] == $nums[$i]) { $i ++; } } return $res; } $nums = [-1, 0, 1, 2, -1, -4]; $three = threeSum($nums); var_dump($three);
相关文章推荐
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 【白话经典算法系列之十一】一道有趣的GOOGLE面试题 --【解法2】 .
- 白话经典算法系列之十一 一道有趣的GOOGLE面试题 --【解法2】
- 经典算法面试题系列(一)——tow sum
- 【白话经典算法系列之十一】一道有趣的GOOGLE面试题 --【解法2】
- 【白话经典算法系列之十二】数组中只出现1次的两个数字(百度面试题)
- 白话经典算法系列之十二 数组中只出现1次的两个数字(百度面试题)
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 【白话经典算法系列之十二】数组中只出现1次的两个数字(百度面试题)
- 【BAT经典算法面试题系列】求和为n的连续正整数
- 经典基础算法之面试题(系列一)
- 白话经典算法系列之十 一道有趣的GOOGLE面试题 .
- 【白话经典算法系列之十二】数组中只出现1次的两个数字(百度面试题)
- 经典算法研究系列:三、动态规划算法解微软一道面试题[第56题]
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 【BAT经典算法面试题系列】求和为n的连续正整数
- 白话经典算法系列之十 一道有趣的GOOGLE面试题
- 【白话经典算法系列之十一】一道有趣的GOOGLE面试题 --【解法2】