Algorithm(218)
-
Hanoi top
list1 = [5,4,3,2,1] def pm(start,end): print(f"{start} ---> {end}") def hanoi(n,start,end): if n == 1: pm(start,end) else: other = 6 - start - end hanoi(n-1,start,other) pm(start,end) hanoi(n-1,other,end)hanoi(3,1,3)
2024.07.21 -
[Leetcode]234. Palindrome Linked List
class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: def recursive_check(current: ListNode) -> bool: nonlocal front_pointer if current is not None: if not recursive_check(current.next): return False if current.val != front_pointer.val: return False f..
2024.07.21 -
[Leetcode]21. Merge Two Sorted Lists
1. 문제 You are given the heads of two sorted linked lists list1 and list2.Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.Return the head of the merged linked list. Example 1:Input: list1 = [1,2,4], list2 = [1,3,4]Output: [1,1,2,3,4,4]Example 2:Input: list1 = [], list2 = []Output: []Example 3:Input: list1 = [], list2 = [0]Out..
2024.07.20 -
[Leetcode]509. Fibonacci Number
문제:The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,F(0) = 0, F(1) = 1F(n) = F(n - 1) + F(n - 2), for n > 1.Given n, calculate F(n). Example 1:Input: n = 2Output: 1Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. solution:첫 번째## solution1 : recursive tree; time compl..
2024.07.19 -
[Leetcode]206. Reverse Linked List
1. 재귀를 이용한 풀이 일단, 그렇게 효율적이지는 않다는 생각이 드는 코드다. 왜냐하면, 코드를 짜는 게 어렵기 때문이다. 언젠가는 재귀함수를 정복하겠다.class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = nextclass Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # Base case: if the list is empty or has only one node if not head or not head.next: return ..
2024.07.17 -
[Leetcode] 154. Find Minimum in Rotated Sorted Array II
Problem: Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become: [4,5,6,7,0,1,4] if it was rotated 4 times. [0,1,4,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]. Given the sorted rotate..
2024.04.10