LeetCode #8
What I’ve Learned
First, We can append length of array by digits = new int[digits.length + 1];
Second, To return in String and for appending, we can use StringBuilder.
Disclaimer
My LeetCode is free plan. I am posting just the free algorithms for now on. Also, I am using JAVA to code.
9. Palindrome Number Review
Solution
I was able to come up with the idea of reversing integer, but I didn’t know how. Solution was simple. Using digit
and temp
. We are multipling and adding reversely by using int digit
.
class Solution {
public boolean isPalindrome(int x) {
if(x < 0){
return false;
}
long reversed = 0;
long temp = x;
while(temp != 0){
int digit = (int) (temp % 10);
reversed = reversed * 10 + digit;
temp /= 10;
}
return (reversed == x);
}
}
70. Climbing Stairs
Solution
This is hard. I’ve came up with using Combination. Counting 1s and adding where to fit 2. But, if number gets bigger, it takes longer. So, there is a problem with it. I never thought of recursion so, I wasn’t able to solve this problem. I’ve saw the solution but, surprisingly this solution had problem too. The ** Time Limit Exceeded **.
class Solution {
public int climbStairs(int n) {
if(n==0 || n==1){
return 1;
}
return climbStairs(n-1) + climbStairs(n-2);
}
}
66. Plus One
My Solution
When given ListNode, I need to think about array. ArrayList<ListNode> arr = ArrayList<>();
. But, this didn’t work. It seems it’s not working after 3 values.
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ArrayList<ListNode> arr = new ArrayList<>();
arr.add(head);
head = head.next;
while(head!=null){
if(arr.get() == head)
head = head.next;
else{
arr.add(head);
head = head.next;
}
}
ListNode pointer = arr.getFirst();
return pointer.next;
}
}
Solution
By adding ListNode res
, we can just solve it without importing ArrayList
. I’ve never used head.val
before.
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode res = head;
while(head != null && head.next != null){
if(head.val == head.next.val){
head.next = head.next.next;
} else{
head = head.next;
}
}
return res;
}
}