题目英文
Given an array nums
of n integers, are there elements a, b, c
in nums
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],A solution set is:
[[-1, 0, 1],[-1, -1, 2]
]
题目中文
给定一个包含 n 个整数的数组nums
,判断nums
中是否存在三个元素a,b,c
,使得a + b + c = 0
?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],满足要求的三元组集合为:
[[-1, 0, 1],[-1, -1, 2]
]
算法实现
public class Solution {public IList<IList<int>> ThreeSum(int[] nums) {IList<IList<int>> result = new List<IList<int>>();if (nums == null || nums.Length < 3)return result;nums = nums.OrderBy(a => a).ToArray();int len = nums.Length;for (int i = 0; i < len; i++){if (nums[i] > 0) // 如果当前数字大于0,则三数之和一定大于0,所以结束循环break;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){result.Add(new List<int>() {nums[i], nums[l], nums[r]});while (l < r && nums[l] == nums[l + 1]) l++; // 去重while (l < r && nums[r - 1] == nums[r]) r--; //去重l++;r--;}else if (sum < 0){l++;}else if (sum > 0){r--;}}}return result; }
}
实验结果
- 状态:通过
- 313 / 313 个通过测试用例
- 执行用时:468 ms
相关图文:
- LeetCode实战:删除链表的倒数第N个节点
- LeetCode实战:合并两个有序链表
- LeetCode实战:两两交换链表中的节点
- LeetCode实战:旋转链表
- LeetCode实战:相同的树
- LeetCode实战:对称二叉树
- LeetCode实战:二叉树的最大深度
- LeetCode实战:搜索二维矩阵
- LeetCode实战:将有序数组转换为二叉搜索树
- 资料分享:数学建模资料分享 – 图论部分
- 资料分享:数学建模资料分享 – 神经网络部分
- 如何利用 C# 实现 K 最邻近算法?
- 如何利用 C# 实现 K-D Tree 结构?
- 如何利用 C# + KDTree 实现 K 最邻近算法?
- 如何利用 C# 对神经网络模型进行抽象?
- 如何利用 C# 实现神经网络的感知器模型?
- 如何利用 C# 实现 Delta 学习规则?
- 如何利用 C# 实现 误差反向传播 学习规则?
- 如何利用 C# 爬取带 Token 验证的网站数据?
- 如何利用 C# 向 Access 数据库插入大量数据?
- 如何利用 C# + Python 破解猫眼电影的反爬虫机制?