leetcode practice - python3 (14)

621. Task Scheduler

DescriptionHintsSubmissionsDiscussSolution
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.

However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return the least number of intervals the CPU will take to finish all the given tasks.

Example 1:
Input: tasks = [“A”,”A”,”A”,”B”,”B”,”B”], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].

思路:优先队列

import queue

class Solution:
    def leastInterval(self, tasks, n):
        """
        :type tasks: List[str]
        :type n: int
        :rtype: int
         """
        counts = [0] * 26
        for t in tasks:
            counts[ord(t) - ord('A')] += 1

        pq = queue.PriorityQueue()
        for c in counts:
            if c != 0:
                pq.put(-c)

        ans = 0
        while not pq.empty():
            tmp = []
            i = 0
            while i <= n:
                if not pq.empty():
                    v = pq.get()
                    if -v > 1:
                        tmp.append(v+1)
                ans += 1
                if pq.empty() and len(tmp) == 0:
                    break
                i += 1

            for t in tmp:
                pq.put(t)

        return ans

Time Limit Exceeded

思路:计算空闲时间
例如 5*A,5*B,3*C,2*D,1*E,n=6
A B C D E *
A B C D * *
A B C * * *
A B * * * *
A B
除了最后一次,上面必须补全n,假设最多的任务A次数max,令m = max-1,则需要补全的方阵为x = m * (n+1),
idle数为x - min(counts(A), m) - min(counts(B), m) - …. - min(counts(E), m)
下面实现x = m * n,然后不减 min(counts(A), m),跟上面等价

class Solution:
    def leastInterval(self, tasks, n):
        """
        :type tasks: List[str]
        :type n: int
        :rtype: int
        """
        if n == 0:
            return len(tasks)

        counts = [0] * 26
        for t in tasks:
            counts[ord(t) - ord('A')] += 1
        counts.sort(reverse = True)

        m = counts[0] - 1
        idle = m * n
        i = 1
        while i < 26 and counts[i] > 0:
            idle -= min(counts[i], m)
            i += 1

        return len(tasks) + (idle if idle > 0 else 0)

Beat 73.96% python3 2018-06-08

思路:
A B C D E *
A B C D * *
A B C * * *
A B * * * *
A B
设出现最多次数的任务出现了m次,则最后一轮时间为任务数m的任务个数,此处为2(A,B),
上面所需时间(m-1) * (n+1)

class Solution:
    def leastInterval(self, tasks, n):
        """
        :type tasks: List[str]
        :type n: int
        :rtype: int
        """
        counts = collections.Counter(tasks).values()
        m = max(counts)
        return max(len(tasks), (m-1)*(n+1) + list(counts).count(m))

Beat 100.0% python3 2018-06-08

148. Sort List

DescriptionHintsSubmissionsDiscussSolution
Sort a linked list in O(n log n) time using constant space complexity.

Example 1:
Input: 4->2->1->3
Output: 1->2->3->4

Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5

思路:merge sort

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p = head
        length = 0
        while p:
            length += 1
            p = p.next

        return self.mergeSort(head, length)

    def mergeSort(self, head, length):
        if length <= 1:
            return head

        prev, mid = None, head
        for i in range(length//2):
            prev = mid
            mid = mid.next

        if prev:
            prev.next = None

        left = self.mergeSort(head, length//2)
        right = self.mergeSort(mid, length - length//2)

        return self.merge(left, right)

    def merge(self, l1, l2):
        if l1 is None:
            return l2
        if l2 is None:
            return l1

        head = None
        if l1.val < l2.val:
            head = l1
            l1 = l1.next
        else:
            head = l2
            l2 = l2.next
        tail = head

        while l1 and l2:
            if l1.val < l2.val:
                tail.next = l1
                tail = l1
                l1 = l1.next
            else:
                tail.next = l2
                tail = l2
                l2 = l2.next

        if l1:
            tail.next = l1
        elif l2:
            tail.next = l2

        return head

Beat 91.02% python3 2018-06-09

思路:使用额外空间

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p = head
        l = []
        while p:
            l.append(p.val)
            p = p.next

        l.sort()
        p = head
        for n in l:
            p.val = n
            p = p.next

        return head

Beat 100.0% python3 2018-06-09

114. Flatten Binary Tree to Linked List

DescriptionHintsSubmissionsDiscussSolution
Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:

1
\
2
\
3
\
4
\
5
\
6

思路:DFS,记录prev节点

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        def dfs(root):
            if self.prev:
                self.prev.right = root

            if root:
                left = root.left
                right = root.right

                root.left = None
                self.prev = root

                dfs(left)
                dfs(right)

        self.prev = None
        dfs(root)

Beat 96.10% python3 2018-06-10

128. Longest Consecutive Sequence

DescriptionHintsSubmissionsDiscussSolution
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

思路:使用Hash表,出现任意数字时查包含该数字的最长序列

class Solution:
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        d = {n : 1 for n in nums}
        ans = 0
        for n in nums:
            if d[n] == 0:
                continue

            l = n - 1
            while l in d:
                l -= 1

            r = n + 1
            while r in d:
                r += 1

            if r - l - 1 > ans:
                ans = r - l - 1

            d[n] = 0

        return ans

Time Limit Exceeded

优化:检查过的数字都不重复查

class Solution:
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        d = {n : 1 for n in nums}
        ans = 0
        for n in nums:
            if d[n] == 0:
                continue

            d[n] = 0

            l = n - 1
            while l in d:
                d[l] = 0
                l -= 1

            r = n + 1
            while r in d:
                d[r] = 0
                r += 1

            if r - l - 1 > ans:
                ans = r - l - 1

        return ans

Beat 99.73% python3 2018-06-11

35. Search Insert Position

DescriptionHintsSubmissionsDiscussSolution
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:
Input: [1,3,5,6], 5
Output: 2

Example 2:
Input: [1,3,5,6], 2
Output: 1

Example 3:
Input: [1,3,5,6], 7
Output: 4

Example 4:
Input: [1,3,5,6], 0
Output: 0

思路:lower_bound

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        l, r = 0, len(nums)-1
        while l <= r:
            m = (l + r) // 2
            if nums[m] < target:
                l = m + 1
            else:
                r = m - 1
        return l

Beat 99.88% python3 2018-06-11

思路:使用python3库 bitsect.bisect_left

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        return bisect.bisect_left(nums,target)

Beat 99.88% python3 2018-06-11

猜你喜欢

转载自blog.csdn.net/guzhou_diaoke/article/details/80644095
今日推荐