From 782e760596663afa743ff89891e1fae446cebc9f Mon Sep 17 00:00:00 2001 From: gameloader Date: Fri, 22 Mar 2024 20:43:33 +0800 Subject: [PATCH] leetcode update --- content/posts/leetcode.md | 113 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index ce26fed..9fdd750 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -1748,3 +1748,116 @@ func reverseList(head *ListNode) *ListNode { return head } ``` + +## day25 2024-03-22 + +### 234. Palindrome Linked + +Given the head of a singly linked list, return true if it is a palindrome or false otherwise. + +![03220NcGLgVTEmnC](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/03220NcGLgVTEmnC.png) + +### 题解 + +本题也是一道基础题, 使用快慢指针的方法遍历到链表的中间, 在遍历的同时将链表的前半部分的值保存到数组中, 再从中间继续向后遍历, 遍历的同时反向遍历数组, 比较遍历的节点和遍历到的数组中元素的值. 若不同则不是回文, 直到全部遍历完成为止. + +### 代码 + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func isPalindrome(head *ListNode) bool { + back := head + before:= head + if head.Next != nil{ + before = head.Next + }else{ + return true + } + values := []int{head.Val} + for before!= nil && before.Next != nil{ + back = back.Next + values = append(values, back.Val) + before = before.Next.Next + } + if before == nil{ + for i:=len(values)-2;i>=0;i--{ + back = back.Next + if back.Val != values[i]{ + return false + } + } + return true + }else{ + for i:= len(values)-1;i>=0;i--{ + back =back.Next + if back.Val != values[i]{ + return false + } + } + return true + } +} +``` + +### 总结 + +查看用时较短的题解, 使用了快慢指针, 找到中间位置后将后半截链表反转, 然后从原始链表头部和反转的后半截链表头部开始依次遍历并比较即可. 这种方法时间复杂度为O(n), 空间复杂度为O(1), 代码如下 + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func isPalindrome(head *ListNode) bool { + + + slow:=head + fast:=head.Next + + for fast!=nil && fast.Next!=nil{ + slow=slow.Next + fast=fast.Next.Next + } + + second:=slow.Next + slow.Next=nil + + second=reverse(second) + + for second!=nil && head!=nil{ + + + if second.Val!=head.Val{ + return false + } + second=second.Next + head=head.Next + } + return true + +} + +func reverse(head *ListNode) *ListNode{ + + var prev *ListNode + var futr *ListNode + + for head!=nil{ + futr=head.Next + head.Next=prev + prev=head + head=futr + } + + return prev +} +```