๋ฌธ์
https://leetcode.com/problems/add-two-numbers-ii/description/
์ฃผ์ด์ง ๋๊ฐ์ ๋น์ด์์ง ์์ linked list๋ ๊ฐ๊ฐ ์์๊ฐ ์๋ ์ ์๋ก ์ด๋ฃจ์ด์ ธ์๋ค. ๊ฐ์ฅ ์ค์ํ ์ซ์๊ฐ ์ฒซ๋ฒ์งธ๋ก ์ค๋ฉฐ, ๊ทธ๋ค์ ๋ ธ๋ ๊ฐ๊ฐ์ ํ์๋ฆฌ ์๋ฅผ ํฌํจํ๋ค. ๋ ์ซ์๋ฅผ ๋ํ ํฉ์ linked list ํํ๋ก ๋ฐํํ๋ผ.
๋ ์ซ์๋ 0์ผ ๊ฒฝ์ฐ๋ฅผ ์ ์ธํ๊ณ , ์์๋ฆฌ๊ฐ 0์ผ๋ก ๋ํ๋์ง ์๋๋ค.
ํ์ด
Stack์ ์ฌ์ฉํ ํ์ด
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ArrayDeque<Integer> st1 = new ArrayDeque<>();
ArrayDeque<Integer> st2 = new ArrayDeque<>();
while (l1 != null) {
st1.push(l1.val);
l1 = l1.next;
}
while (l2 != null) {
st2.push(l2.val);
l2 = l2.next;
}
ListNode result = null;
int carry = 0;
while (!st1.isEmpty() || !st2.isEmpty() || carry > 0) {
int v1 = (!st1.isEmpty()) ? st1.pop() : 0;
int v2 = (!st2.isEmpty()) ? st2.pop() : 0;
int sum = v1 + v2 + carry;
ListNode newNode = new ListNode(sum % 10);
newNode.next = result;
result = newNode;
carry = sum / 10;
}
return result;
}
๋์ฒดํ ArrayDeque๋ฅผ ์คํ ํํ๋ก ์ฌ์ฉ - Stack ๋์ ArrayDeque๋ฅผ ์ฌ์ฉํ๋ ์ด์
๋๋ ListNode๋ฅผ ๋ฐ๋๋ก ๋ค์ง์ด, ๋์ผํ๊ฒ ํ๋์ฉ ๋ํ๋ ๋ฐฉ๋ฒ๋ ์๊ฒ ๋ค.
์๊ฐ ๋ณต์ก๋: O(max(n+m)), ๊ณต๊ฐ ๋ณต์ก๋: O(n+m)
https://github.com/jeongum/java-algorithm/blob/master/stack/LeetCode_445_AddTwoNumbers.java
'๐ ์๊ณ ๋ฆฌ์ฆ > ์๋ฃ๊ตฌ์กฐ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 225. Implement Stack using Queues (ํด์, Java ํ์ด) (0) | 2023.08.28 |
---|---|
[LeetCode] 735. Asteroid Collision (ํด์, Java ํ์ด) (0) | 2023.07.21 |
[SWEA] 1223๋ฒ ๊ณ์ฐ๊ธฐ2 (Java) (0) | 2021.08.20 |
[๋ฐฑ์ค]1158๋ฒ ์์ธํธ์ค๋ฌธ์ (0) | 2021.08.10 |
[๋ฐฑ์ค]1918๋ฒ ํ์ํ๊ธฐ์ (0) | 2021.08.09 |