15. 3Sum

2018/05/06 leetcode 共 918 字,约 3 分钟

Title

the problem link

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

Solution

//cpp:
class Solution {
public:
	vector<vector<int>> threeSum(vector<int>& nums) {
		vector<vector<int>> res;
		sort(nums.begin(), nums.end());
		for (int i = 0; i < nums.size(); i++) {
			if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {
				int lo = i + 1, hi = nums.size() - 1, sum = 0 - nums[i];
				while (lo < hi) {
					if (nums[lo] + nums[hi] == sum) {
						res.push_back({ nums[lo],nums[hi], nums[i] });
						while (lo < hi&&nums[lo] == nums[lo + 1]) lo++;
						while (lo < hi&&nums[hi] == nums[hi - 1]) hi--;
						lo++, hi--;

					}
					else if (nums[lo] + nums[hi] < sum) {
						lo++;
					}
					else {
						hi--;
					}
				}
			}
		}
		return res;
	}
};

Search

    Table of Contents