๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/๋ฌธ์ œ

[์ž๋ฐ”] Leetcode 234 - Palindrome Linked List

by applemango2021 2021. 3. 1.
  • ์ตœ์ ํ™”๋œ ๋ฐฉ๋ฒ•์€ ์•„๋‹ˆ๋‹ค. ์ผ๋‹จ Linked List๋ฅผ ๋๊นŒ์ง€ ํƒ€๋ฉด์„œ ArrayList<Integer> list์— ๋‹ด์•„์ฃผ๊ณ , ๊ทธ list์˜ ์–‘ ๋๊ฐ’๋“ค์„ ํ•˜๋‚˜์”ฉ ๋น„๊ตํ•ด๊ฐ€๋ฉด์„œ ์–ด๊ธ‹๋‚˜๋Š” ๊ฒŒ ์žˆ์œผ๋ฉด ๋ฐ”๋กœ answer = false๋ฅผ ๋„ฃ๊ณ  ๋‚˜์™€๋ฒ„๋ฆฐ๋‹ค. 
  • Linked List๋ฅผ ์ˆœํšŒํ•˜๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„ O(n) + ArrayList์˜ ์ ˆ๋ฐ˜์„ ์ˆœํšŒํ•˜๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„ O(n/2)ํ•ด์„œ ๊ฒฐ๊ตญ ๋Œ€๋žต O(n)์ด๊ธฐ๋Š” ํ•œ๋ฐ, ์„ฑ๋Šฅ์ด ํ•˜์œ„ 70%์— ์†ํ•œ๋‹ค ใ…Ž

  • ์‹œ๊ฐ„์ด ๋น ๋ฅธ ๋‹ค๋ฅธ ํ’€์ด๋ฅผ ๋ณด๋ฉด ๋‘ ๊ฐœ์˜ ๋ณ€์ˆ˜ (fast, slow)๋ฅผ ์จ์„œ ๋ญ”๊ฐ€๋ฅผ ํ•˜๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ, ์ดํ•ด๋Š” ๋‚˜์ค‘์— ํ•ด์•ผ๊ฒ ๋‹ค!

  • ์ฒ˜์Œ ์ œ์ถœํ–ˆ์„ ๋•Œ, [-129, -129] ์ผ€์ด์Šค์—์„œ Wrong Answer๊ฐ€ ๋‚˜์™”๋‹ค. ์ผ๋‹จ ์ž˜๋ชป ์ƒ๊ฐํ–ˆ๋˜ ์ ์€, ์ž๋ฐ”๋ฅผ ๋„ˆ๋ฌด ๊ฒ‰ํ•ฅ๊ธฐ ์‹์œผ๋กœ ํ–ˆ์–ด์„œ ๊ทธ๋Ÿฐ์ง€ Integer๋„ ๊ฐ์ฒด๋ผ๋Š” ์‚ฌ์‹ค์„ ๊นœ๋นกํ•˜๊ณ  ๋ฐ”๋กœ ๊ทธ๋ƒฅ == ์—ฐ์‚ฐ์ž๋กœ ๋น„๊ตํ•ด๋ฒ„๋ฆฐ ๊ฒƒ! intValue() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ฃผ์†Œ๊ฐ’์ด ์•„๋‹Œ ์‹ค์ œ ๊ฐ’์„ ๋น„๊ตํ•ด์ค˜์•ผ ํ•œ๋‹ค. 

 

  • ๊ทผ๋ฐ ์•„๋ฌด๋ฆฌ ์ƒ๊ฐํ•ด๋„ ์ด์ƒํ–ˆ๋‹ค. ์™œ ๋‹ค๋ฅธ ์ผ€์ด์Šค๋“ค์€ ๋งž์•˜์ง€..?  ๊ทธ๋ž˜์„œ ์ฐพ์•„๋ณด๋‹ˆ๊นŒ ์•„๋ž˜ ๋‚ด์šฉ์—์„œ ๋‹ต์„ ์–ป์—ˆ๋‹ค. IntegerCache ํด๋ž˜์Šค์—์„œ ~128๋ถ€ํ„ฐ 127๊นŒ์ง€๋Š” auto-boxing์ด ๋˜๋„๋ก ๊ด€๋ฆฌ๋ฅผ ํ•ด์ค€๋‹ค๊ณ  ํ•œ๋‹ค! ๊ทธ๋Ÿฌ๋‹ˆ ๋”ฑ -129์—์„œ๋Š” ์—๋Ÿฌ๊ฐ€ ๋‚ฌ์ง€๋งŒ, ๋‹ค๋ฅธ ์ผ€์ด์Šค์—์„œ๋Š” ์—๋Ÿฌ๊ฐ€ ์•ˆ ๋‚œ ๊ฒƒ! 

meetup.toast.com/posts/185

 

[Java] Integer.valueOf(127) == Integer.valueOf(127) ๋Š” ์ฐธ์ผ๊นŒ์š”? : NHN Cloud Meetup

[Java] Integer.valueOf(127) == Integer.valueOf(127) ๋Š” ์ฐธ์ผ๊นŒ์š”?

meetup.toast.com


  • ์ „์ฒด ์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        boolean answer = true;
        
        ArrayList<Integer> list = new ArrayList<Integer>();
        
        ListNode node = head;
        while(node!=null){
            list.add(node.val);
            node = node.next;
        }
        
        int len = list.size();
        for(int i=0;i<(len/2);i++){
            
            if(list.get(i).intValue() != list.get(len-i-1).intValue()){
                answer = false;
                break;
            }
        }
        return answer;
    }
}