Daily LeetCode 15. 3Sum
https://leetcode.com/problems/3sum/
Medium
问题描述
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:
1 | Given array nums = [-1, 0, 1, 2, -1, -4], |
思路及代码
这一题要求从一个数组中找三个数,确保三个数的和为零,返回所有的和为零的三个数组成的数组。
首先,我们对数组进行排序,对升序数组进行遍历,在遍历过程中,我们使用双指针寻找另外两个数。
如果当前遍历到的数大于零,我们可以结束遍历,因为此时数组是升序的,三个正数的和不可能为零;如果当前遍历到的数与前一个数相等,那么就跳过这个数,因为结果需要删除重复结果。
假设当前遍历到了nums[i],我们设置左指针left_index=i+1, right_index=len(nums)-1
,当前sum = nums[i] + nums[left_index] + nums[right_index]
,此时根据sum的情况进行下一步操作:
- sum>0:说明当前取的正数偏大,将右指针左移
- sum<0:说明当前取的负数偏小,将左指针右移
- sum=0:将当前三个数加入结果,并且将左右指针移到没有重复元素的位置
代码:
1 | class Solution: |