leetcode update

This commit is contained in:
gameloader 2024-03-22 20:43:33 +08:00
parent e056861b08
commit 782e760596

View File

@ -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
}
```