leetcode之3Sum问题
问题描述:
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],
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
[
[-1, 0, 1],
[-1, -1, 2]
]
问题来源:3Sum
(详细地址:https://leetcode.com/problems/3sum/description/)
思路:
这道题和我上篇博客的意思其实是一样的,只是换了一个说法而已,不过这道题必须先要排序,才能采用上道题的思路。
第一步:对给定数组进行排序;
第二步:固定住数组中的一个,该数相当于Two Sum问题中的target;
第三步:给定首尾两个指针,同时移动两个指针,判断这两个指针所指向的数加上target之后是否为0,有下面三种情况:
1)如果三个数之和确实是0,则只需要把结果添加到最终结果中即可;
2)如果三个数之和大于0,说明右边的指针所指向的数大了,需要把右边的指针往左移动;
3)如果三个数之和小于0,说明左边的指针所指向的数小了,需要把左边的指针往右移动。
代码:
主体部分:
函数具体实现: