【LeetCode】234. Palindrome Linked List 解題報告
234. Palindrome Linked List / Easy
Given the head
of a singly linked list, return true
if it is a palindrome.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Constraints:
- The number of nodes in the list is in the range [1, 10^5].
- 0 <= Node.val <= 9
- Follow up: Could you do it in O(n) time and O(1) space?
Solution
思路
比較簡單的方法是,先將 list 的數字放入一個 vector,再用其他方式判斷是不是迴文。
如果要在 in-place 做的話,思維如下
- 將 list 從中間斷開
- reverse 後半部的 list
- 判斷兩個 list 是否相等
關於第一步,要找出 list 的中點可以使用快慢指標,當快指標到達尾部時,慢指標會在中點。
第二步則可以參考 Leetcode 206. Reverse Linked List
效能
Complexity
- Time Complexity: O(N), where N is the length of the linked list
- Space Complexity: O(1)
LeetCode Result
- Runtime: 241 ms
- Memory Usage: 114 MB
- https://leetcode.com/submissions/detail/726386248/
Code
1 | class Solution { |