๐Ÿฅž BE
home

15_3Sum

๋‹ด๋‹น์ž
์™„๋ฃŒ ์—ฌ๋ถ€
Solved
์š”์•ฝ
๋‚ ์งœ
2024/07/02
ํƒœ๊ทธ
์ž๋ฃŒ๊ตฌ์กฐ
์ด์ง„ํƒ์ƒ‰
๋‚œ์ด๋„
Medium
์ถœ์ฒ˜
LeetCode

์ฝ”๋“œ

import java.util.ArrayList; import java.util.Arrays; import java.util.List; class Solution { // ํˆฌ ํฌ์ธํ„ฐ public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> ans = new ArrayList<>(); Arrays.sort(nums); // 0์ œ์™ธ ์ค‘๋ณต ๊ฑด๋„ˆ๋›ฐ๊ธฐ for (int i = 0; i < nums.length - 2; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } int left = i + 1; int right = nums.length - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum == 0) { // ์ถœ๋ ฅ ํ˜•์‹ ๋งž์ถ”๊ธฐ asList ans.add(Arrays.asList(nums[i], nums[left], nums[right])); // ์ค‘๋ณต ์ˆซ์ž๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ๋‹ค๋ฅธ๊ฑฐ ๋‚˜์˜ฌ๋•Œ๊นŒ์ง€ ๊ฑด๋„ˆ๋›ฐ๊ธฐ while (left < right && nums[left] == nums[left + 1]) { left++; } while (left < right && nums[right] == nums[right - 1]) { right--; } left++; right--; } else if (sum < 0) { left++; } else { right--; } } } return ans; } }
Java
๋ณต์‚ฌ

๋ฌธ์ œ ํ•ด๊ฒฐ ์•„์ด๋””์–ด

์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ™œ์šฉํ•ด ํˆฌํฌ์ธํ„ฐ๋กœ ์ˆœํšŒํ•˜๋ฉฐ 0์ธ ๊ฐ’์„ ์ฐพ์œผ๋ฉด ๋˜๋Š” ๋ฌธ์ œ.