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

题目:

给你一个整数数组 nums ,判断是否存在三元组 nums\[i, numsj, numsk] 满足 i != j、i != k 且 j != k ,同时还满足 numsi + numsj + numsk == 0 。

请你返回所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

C++:

双指针法:

cpp 复制代码
#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:

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

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
相关推荐
Sw1zzle15 小时前
算法入门(四):二叉树 - 递归遍历三件套
算法·leetcode
万法若空15 小时前
【算法-查找】查找算法
java·数据结构·算法
海石15 小时前
子树怎么找?树的3种遍历方式来帮忙!
算法·leetcode
海石15 小时前
难度分 1588:思路 + 技巧 = AC
算法·leetcode
珠海西格电力19 小时前
云边端协同架构:零碳园区管理系统的技术底座
大数据·运维·人工智能·算法·架构·能源
还有多久拿退休金21 小时前
让飞书知识库跟着 commit 自己长:一套自动化知识库的真实实现
前端·算法·架构
KaMeidebaby1 天前
卡梅德生物技术快报|小 RNA 适配体合成 + 多方法亲和力表征全流程标准化操作手册
前端·网络·数据库·人工智能·算法
是Dream呀1 天前
基于深度学习的人类行为识别算法研究
人工智能·深度学习·算法
happyprince1 天前
03_NVIDIA_ModelOpt-量化算法深入
人工智能·深度学习·算法
大鱼>1 天前
AI+货物追踪:智能快递柜追踪系统
人工智能·深度学习·算法·机器学习