[LeetCode] 445. add Two Numbers 2 (ν΄μ, Java νμ΄)
λ¬Έμ
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