leetcode 15. 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
题解:
1.一个包含 n 个整数的数组
2.从数组中找三个数和为0
3.满足条件的作为一组存到列表返回
4.结果去掉重复的三元组
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[[-1, 0, 1],
[-1, -1, 2]]
解题思路:
-
题目明确说明了和为0,先对数组从小到大排序
-
个数不够三个元素的直接返回空结果
-
如果暴力搜索时间肯定是无法允许的,然而还得找出三个数,考虑把找三个数转化为找两个数问题,即要固定一个数,第一个因子从头到尾遍历,当确定这个数不动时找其余两个数
-
先对排序后的数组去重,即相邻元素相同直接跳过
-
排序后的数组从小到大排列,当固定当前元素时,从剩下的元素里左右两边向内逐个找剩余两个数
-
如果三个数和为0,生成三元组加到结果列表里
-
同时也要考虑这两个数的去重复,处理方法相邻元素相同跳过
-
如果不等于0,那么大于0或者小于0
-
大于0,说明正数多,右指针左移,去掉最右边正数
-
小于0,说明负数多,左指针右移动,去掉最左边负数
C/C++题解:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
sort(nums.begin(),nums.end()); // 排序
int len = nums.size();//数组不够三个直接返回空
if(len < 3) return ans;
for (int i = 0; i < len ; i++) {
if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
if(i > 0 && nums[i] == nums[i-1])
continue; // 去重,排完顺序可以这样去重
//从剩余元素里找三个数
int L = i+1;//剩余元素左指针
int R = len-1;//右指针
while(L < R){//剩余元素由外向内找,从找三个数变为找两个
int sum = nums[i] + nums[L] + nums[R];
if(sum == 0){//如果等于0加到结果列表
ans.push_back({nums[i],nums[L],nums[R]});
while (L<R && nums[L] == nums[L+1]) L++; // 去重
while (L<R && nums[R] == nums[R-1]) R--; // 去重
L++;
R--; }//因为从小到大有序
else if (sum < 0) L++;//小于0,负数多左指针右移
else if (sum > 0) R--;} }//大于0,正数多右指针左移
return ans;}};
Debug结果:
Java题解:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList();
Arrays.sort(nums); // 排序
int len = nums.length;//数组不够三个直接返回空
if(nums == null || len < 3) return ans;
for (int i = 0; i < len ; i++) {
if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
if(i > 0 && nums[i] == nums[i-1])
continue; // 去重,排完顺序可以这样去重
//从剩余元素里找三个数
int L = i+1;//剩余元素左指针
int R = len-1;//右指针
while(L < R){//剩余元素由外向内找,从找三个数变为找两个
int sum = nums[i] + nums[L] + nums[R];
if(sum == 0){//如果等于0加到结果列表
ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
while (L<R && nums[L] == nums[L+1]) L++; // 去重
while (L<R && nums[R] == nums[R-1]) R--; // 去重
L++;
R--; }//因为从小到大有序
else if (sum < 0) L++;//小于0,负数多左指针右移
else if (sum > 0) R--;}} //大于0,正数多右指针左移
return ans;}}
Debug结果:
Python题解:
class Solution(object):
def threeSum(self, nums):
""":type nums: List[int]:rtype: List[List[int]]"""
ans = []
nums.sort() # 排序
leng = len(nums) #数组不够三个直接返回空
if leng < 3: return ans
for i in range(leng):
if nums[i] > 0: break #如果当前数字大于0,则三数之和一定大于0,所以结束循环
if i > 0 and nums[i] == nums[i-1]:
continue #去重,排完顺序可以这样去重
#从剩余元素里找三个数
L = i+1 #剩余元素左指针
R = leng-1 #右指针
while L < R: #剩余元素由外向内找,从找三个数变为找两个
sumV = nums[i] + nums[L] + nums[R]
if sumV == 0: #如果等于0加到结果列表
ans.append([nums[i],nums[L],nums[R]]);
while L<R and nums[L] == nums[L+1]: L+=1 #去重
while L<R and nums[R] == nums[R-1]: R-=1 # 去重
L += 1
R -= 1
#因为从小到大有序
elif sumV < 0: L+=1 #小于0,负数多左指针右移
elif sumV > 0: R-=1 #大于0,正数多右指针左移
return ans
Debug结果:
更多题解移步公众号免费获取