Press "Enter" to skip to content

Posts tagged as “3sum”

花花酱 LeetCode 16. 3Sum Closest

Problem

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution: Sorting + Two Pointers

Similar to 花花酱 LeetCode 15. 3Sum

Time complexity: O(n^2)

Space complexity: O(1)

C++

Java

Python3

花花酱 LeetCode 15. 3Sum

题目大意:给你一个数组,让你找出3个数的和为0的所有组合。

Problem:

https://leetcode.com/problems/3sum/description/

Given an array S of n integers, are there elements abc in S 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.

Solution 1: Hashtable

Time complexity: O(n^2)
Space complexity: O(n)

Solution 2: Sorting + Two pointers

Time complexity: O(nlogn + n^2)

Space complexity: O(1)

C++

Related Problems: