首页 技术 正文
技术 2022年11月14日
0 收藏 918 点赞 3,588 浏览 1273 个字

Given an array nums of n integers, are there elements abc 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]
]Time: O(N^2)
 class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
if nums is None:
return res nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
target = -nums[i]
left = i + 1
right = len(nums) - 1
while left < right:
if nums[left] + nums[right] == target:
lst = [nums[i], nums[left], nums[right]]
res.append(lst)
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif nums[left] + nums[right] < target:
left += 1
else:
right -= 1
return res
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
// skip i as well
if (i > 0 && nums[i - 1] == nums[i]) {
continue;
}
int j = i + 1, k = nums.length - 1;
// j and k cannot meet since may add the same number twice
while (j < k) {
int target = nums[i] + nums[j] + nums[k];
if (target == 0) {
res.add(Arrays.asList(nums[i], nums[j], nums[k]));
j += 1;
while (j < k && nums[j] == nums[j - 1]) {
j += 1;
}
} else if (target < 0) {
j += 1;
} else {
k -= 1;
}
}
}
return res;
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,090
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,567
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,415
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,187
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,823
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,906