leetcode笔记(Python版)待更新

1.反转链表:

class Solution:

    # 返回ListNode

    def ReverseList(self, pHead):

        # write code here

        if pHead == None or pHead.next == None:#若链表为空或只有一个数就直接返回0

            return pHead

        pre = None#定义一个空链表

        while pHead:

            nex = pHead.next

            pHead.next = pre

            pre = pHead#指针后移

            pHead = nex#指针后移

        return pre

2.数组排序 可直接return sorted(arr)

class Solution:

    def MySort(self , arr ):

        len_1 = len(arr)

        list_1 = []

        for i in range(len_1):

            list_1.append(arr[i])

        list_1.sort()

        return list_1

3.判断链表是否有环

class Solution:

    def hasCycle(self , head ):

        # write code here

        if head is None or head.next is None:

            return False

        first = head.next

        last = head.next.next

         

        while last is not None:

            if first.val == last.val:

                return True

            first = first.next

            if last.next is None or last.next.next is None:

                return False

            last = last.next.next

        return False

4.分别按照二叉树先序,中序和后序打印所有的节点。

class Solution:

    def threeOrders(self , root ):

        ans = [[],[],[]]

        def dfs(root):

            if not root:

                return

            ans[0].append(root.val)

            dfs(root.left)

            ans[1].append(root.val)

            dfs(root.right)

            ans[2].append(root.val)

            return

        dfs(root)

        return ans

5.二分查找

class Solution:

    def upper_bound_(self , n , v , a ):

        # write code here

        if a[-1]<v:

            return n+1

        left = 0

        right = n-1

        while left<right:

            mid = (left+right)//2

            if a[mid]>=v:

                right = mid

            if a[mid]<v:

                left = mid+1

        return left+1

猜你喜欢

转载自blog.csdn.net/qq_36816848/article/details/114579968
今日推荐