LeetCode热题100道-Day04
- 如果是负数,则直接返回
false;正数的话,将该数转成字符串,然后两个指针分别指向头和尾,两指针同时向内收缩判断即可
import (
"fmt"
"strconv"
)
func isPalindrome(x int) bool {
if x<0 {
return false
}
str := strconv.Itoa(x)
i := 0
j := len(str)-1
for i<j{
if str[i]!=str[j] {
return false
}
i++
j--
}
return true
}
func singleNumber(nums []int) int {
res := 0
for _, v := range nums {
res ^= v
}
return res
}
- 前后指针,前指针每次走两步,后指针每次走一步,若能相遇,则说明存在环
func hasCycle(head *ListNode) bool {
if head==nil || head.Next==nil {
return false
}
p := head
c := head
for c != nil && c.Next != nil {
p = p.Next
c = c.Next.Next
if p == c {
return true
}
}
return false
}
- 在上一题环形链表的时候,若存在环,则找到第一次相遇点,这时,前面的指针肯定的比后面的指针多走了一圈的距离,这时候,让其中一个指针回到启动,两个指针同时向前走,每次走一步,则下次相遇的点即为环的起点
func detectCycle(head *ListNode) *ListNode {
if head==nil || head.Next==nil {
return nil
}
p := head
c := head
for c != nil && c.Next != nil {
p = p.Next
c = c.Next.Next
if p == c {
break
}
}
if c==nil || c.Next==nil {
return nil
}
p = head
for {
if p==c {
return c
}
p = p.Next
c = c.Next
}
return nil
}
func getIntersectionNode(headA, headB *ListNode) *ListNode {
i := headA
j := headB
for {
if i==j {
return i
}
if i==nil {
i = headB
} else {
i = i.Next
}
if j==nil {
j = headA
} else {
j = j.Next
}
}
return nil
}