56-60題

56、鏈表中倒數(shù)第K節(jié)點(diǎn)
因為之前做了好幾道雙指針的題,所以聯(lián)想到這道題也能用雙指針。
但是不知道為什么不能AC

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if not head:
            return None
        fast, slow = head, head
        for i in range(1, k):
            if not fast:
                return None
            fast = fast.next
        while fast.next:
            fast = fast.next
            slow = slow.next
        return slow

57、合并兩個排序鏈表

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        head = ListNode(-1)
        temp = head
        while l1 and l2:
            if l1.val <= l2.val:
                temp.next = l1
                l1 = l1.next
                temp = temp.next
            else:
                temp.next = l2
                l2 = l2.next
                temp = temp.next
        if l1:
            temp.next = l1
        if l2:
            temp.next = l2
        return head.next

58、翻轉(zhuǎn)鏈表

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        a, b, c = None, head, head.next
        while c:
            b.next = a
            a, b, c = b, c, c.next
        b.next = a
        return b

59、樹的子結(jié)構(gòu)

class Solution:
    def HasSubtree(self, pRoot1, pRoot2):
        # write code here
        if pRoot1 == None or pRoot2 == None:
            return False
        return self.isSubtree(pRoot1, pRoot2)

    def isSubtree(self, p1, p2):
        if p2 == None:
            return True
        if p1 == None:
            return p1 == p2
        res = False
        if p1.val == p2.val:
            res = self.isSubtree(p1.left, p2.left) and self.isSubtree(p1.right, p2.right)
        return res or self.isSubtree(p1.left, p2) or self.isSubtree(p1.right, p2)

60、數(shù)值的整數(shù)次方
看了別人的代碼,利用右移一位運(yùn)算代替除以2
利用位與運(yùn)算代替了求余運(yùn)算法%來判斷一個數(shù)是奇數(shù)還是偶數(shù)

# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        if exponent == 0:
            return 1
        if exponent == 1:
            return base
        if exponent == -1:
            return 1/base

        ans = self.Power(base, exponent >> 1)
        ans = ans * ans
        if exponent & 1 == 1:
            ans = ans * base
        return ans

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 過年那會在家,聽我媽跟我說大廣死了。啊,我一臉的震驚。說是過年那兩天死在了自己家中,他侄子去叫他吃餃子,叫了半天沒...
    矢羽閱讀 534評論 0 2
  • 遇見你,一切都是時光最好的安排。 白日不到處 青春恰自來 苔花如米小 也學(xué)牡丹開 如果沒有那些眼淚灌溉,如今還是那...

友情鏈接更多精彩內(nèi)容