8.15筆記

61. 旋轉鏈表

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or k == 0 or not head.next:
            return head
        count = 1
        cur,tep = head,head
        while cur.next:
            count += 1
            cur = cur.next
        a = k%count
        if a == 0:
            return head
        for i in range(count-a-1):
            tep = tep.next
        res = tep.next
        tep.next = None
        cur.next = head
        return res

40. 組合總和 II

class Solution(object):
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        candidates.sort()
        self.dfs(candidates,0,[],target,res)
        return res
    def dfs(self,nums,start,path,target,res):
        if target == 0:
            res.append(path)
            return
        for i in range(start,len(nums)):
            if start < i and nums[i]==nums[i-1]:
                continue
            if nums[i] > target:
                break
            self.dfs(nums,i+1,path+[nums[i]],target-nums[i],res)

86. 分隔鏈表

class Solution(object):
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        tep = a = ListNode(0)
        res = b = ListNode(0)
        while head:
            if head.val >= x:
                a.next = head
                a = a.next
            else:
                b.next = head
                b = b.next
            head = head.next
        a.next = None
        b.next = tep.next
        return res.next

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章