LeetCode第十五题:三数之和15:,下面我们就来聊聊关于leetcode两数之和怎么算?接下来我们就一起去了解一下吧!

leetcode两数之和怎么算(LeetCode解析第十五题三数之和)

leetcode两数之和怎么算

LeetCode第十五题:三数之和

15:

英文题面:

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] ]

解析:

这个题简单地考虑可以便利所有三元组,复杂度为n^3。

首先将数组排序,磨刀不误砍柴工,这部分复杂度为nlogn。

用一个指针从第一个开始向后遍历,在指向第i个数时,在取两个指针,分别指向下一个与最后一个,即第i 1个和最后一个。根据不同情况移动这后两个指针,若三数之和大于0,则将后指针向前移,否则将前指针向后移。直到这两个指针重合为止。若三数之和等于0,则加入结果中。

,