LeetCode習題整理II

煎餅排序

給定數組 A,我們可以對其進行煎餅翻轉:我們選擇一些正整數 k <= A.length,然後反轉 A 的前 k 個元素的順序。我們要執行零次或多次煎餅翻轉(按順序一次接一次地進行)以完成對數組 A 的排序。

返回能使 A 排序的煎餅翻轉操作所對應的 k 值序列。任何將數組排序且翻轉次數在 10 * A.length 範圍內的有效答案都將被判斷爲正確。

示例 1:

輸入:[3,2,4,1]
輸出:[4,2,4,3]
解釋:
我們執行 4 次煎餅翻轉,k 值分別爲 4,2,4,和 3。
初始狀態 A = [3, 2, 4, 1]
第一次翻轉後 (k=4): A = [1, 4, 2, 3]
第二次翻轉後 (k=2): A = [4, 1, 2, 3]
第三次翻轉後 (k=4): A = [3, 2, 1, 4]
第四次翻轉後 (k=3): A = [1, 2, 3, 4],此時已完成排序。
示例 2:

輸入:[1,2,3]
輸出:[]
解釋:
輸入已經排序,因此不需要翻轉任何內容。
請注意,其他可能的答案,如[3,3],也將被接受。

提示:

1 <= A.length <= 100
A[i] 是 [1, 2, …, A.length] 的排列

class Solution(object):
    def pancakeSort(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        def tranv(A,index):#反轉前k個數
            k=[]
            for i in range(index+1):
                k.append(A[i])
            for i in range(index+1):
                A[i]=k.pop()
            return None
        n=len(A)
        ans=[]
        for i in range(n):
            if n>1:
                index,_=max(enumerate(A[:n]),key=lambda x:x[1])#找到前n個數的最大的索引
                if index >0:
                    tranv(A,index)#前index+1個數反轉
                    ans.append(index+1)
                tranv(A,n-1)
                ans.append(n)
                n-=1
            else:break
        return ans

複製帶隨機指針的鏈表

給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。

要求返回這個鏈表的 深拷貝。

我們用一個由 n 個節點組成的鏈表來表示輸入/輸出中的鏈表。每個節點用一個 [val, random_index] 表示:

val:一個表示 Node.val 的整數。
random_index:隨機指針指向的節點索引(範圍從 0 到 n-1);如果不指向任何節點,則爲 null 。

示例 1:
在這裏插入圖片描述

輸入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
輸出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:

在這裏插入圖片描述

輸入:head = [[1,1],[2,1]]
輸出:[[1,1],[2,1]]
示例 3:
在這裏插入圖片描述

輸入:head = [[3,null],[3,0],[3,null]]
輸出:[[3,null],[3,0],[3,null]]
示例 4:

輸入:head = []
輸出:[]
解釋:給定的鏈表爲空(空指針),因此返回 null。

提示:

-10000 <= Node.val <= 10000
Node.random 爲空(null)或指向鏈表中的節點。
節點數目不超過 1000 。

"""
# Definition for a Node.
class Node:
    def __init__(self, x, next=None, random=None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: Node
        :rtype: Node
        """
        p = head
        result = None
        pre = None
        D = {}
        while p != None:
            node = Node(p.val, random=p.random)
            D[p] = node
            if pre != None:
                pre.next = node
            else:
                result = node
            pre = node
            p = p.next
        
        q = result
        while q != None:
            if q.random != None:
                q.random = D[q.random]
            q = q.next
        
        #print(result.val)
        return result
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章