Leecode热题100---15:三数之和为零

题目:
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。
请你返回所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。

C++:
双指针法:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
	vector<vector<int>> threeSum(vector<int>& nums) {
		int n = nums.size();
		sort(nums.begin(), nums.end()); // 对数组进行排序,以便后续操作
		vector<vector<int>> answer; // 存储结果的二维向量

		for (int i = 0; i < n; i++) { // 遍历数组,固定第一个元素
			// 避免重复的固定元素
			if (i > 0 && nums[i] == nums[i - 1])
				continue;

			int left = i + 1; // 左指针指向固定元素的下一位
			int right = n - 1; // 右指针指向数组末尾

			while (left < right) {
				int sum = nums[i] + nums[left] + nums[right]; // 计算三个元素的和

				if (sum < 0) { // 如果和小于零,说明需要增大和,左指针右移一位
					left++;
				}
				else if (sum > 0) { // 如果和大于零,说明需要减小和,右指针左移一位
					right--;
				}
				else { // 和等于零,找到满足条件的三元组
					answer.push_back(vector<int>{ nums[i], nums[left], nums[right] }); // 将三元组添加到结果中
					cout << 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--; // 右指针左移一位
				}
			}
		}
		return answer;
	}
};

int main()
{
	Solution S;
	vector<int> nums = { -1, 0, 1, 2, -1, -4 };
	vector<vector<int>> answers = S.threeSum(nums);
}

python:
思路:先排序,然后两边向中间靠拢。

class Solution():
    def threeSum(self,nums):
        nums.sort()  # 排序
        res = []
        for i in range(len(nums)):  # 遍历每一个数
            if i==0 or nums[i] > nums[i-1]:  # 确定不重复的数字(开头)
                l = i+1
                r = len(nums)-1
                while l<r:
                    s = nums[i] + nums[l] + nums[r]
                    if s == 0:
                        res.append([nums[i],nums[l],nums[r]])
                        l += 1
                        r -= 1
                        # 左边向右移动到不重复数为止
                        while l<r and nums[l] == nums[l-1] :
                            l += 1
                        # 右边向左边移动不重复数为止
                        while l<r and nums[r] == nums[r+1] :
                            r -= 1
                    elif s >0:
                        r -= 1
                    else:
                        l += 1
        return res
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ghx3110

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值