반응형
문제
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
Example 2:
Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Example 3:
Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
Constraints:
3 <= nums.length <= 3000
-105 <= nums[i] <= 105
https://leetcode.com/problems/3sum
풀이
나열된 숫자에서 3개를 뽑아 확인하는 것이기에 조합(combination)을 생각했다가,
배열이 최대 3000개일 경우 시간복잡도가 2^3000으로 너무 오래걸리기 때문에 다른 방법을 고민하고 코딩했다.
배열을 오름차순으로 정렬하고 하나를 선택한 뒤, 작은 수와 큰 수를 선택하여 조건에 맞는지 비교하는 방법으로 작성했다.
비교를 하지 않고 넘어갈 조건과 중복을 제거할 조건을 좀 더 추가하면 속도가 더 빠를 것 같긴한데,
우선 HashSet을 이용하여 저장할 때부터 중복을 제거하게끔 진행해봤다.
추가적인 조건은 나중에 다시 생각해봐야겠다.
코드
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
HashSet<List<Integer>> res = new HashSet<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++) {
int left = i + 1;
int right = nums.length - 1;
while(left < right) {
if (nums[left] + nums[right] + nums[i] < 0) {
left++;
} else if (nums[left] + nums[right] + nums[i] == 0) {
List<Integer> res_temp = new ArrayList<>();
res_temp.add(nums[i]);
res_temp.add(nums[left]);
res_temp.add(nums[right]);
res.add(res_temp);
left++;
right--;
} else {
right--;
}
}
}
return new ArrayList<>(res);
}
}
결과
Runtime : 299 ms
Memory Usage : 52.81 MB
반응형
'LeetCode' 카테고리의 다른 글
17. Letter Combinations of a Phone Number (0) | 2025.01.14 |
---|---|
16. 3Sum Closest (0) | 2025.01.09 |
14. Longest Common Prefix (0) | 2024.12.27 |
13. Roman to Integer (1) | 2024.12.20 |
12. Integer to Roman (0) | 2024.11.30 |