LeetCode解题报告
  • LeetCode解题报告
  • Easy
    • 1086. High Five
    • 283. Move Zeros
    • 443. String Compression
    • 38. Count and Say
    • 169. Majority Element
    • 349. Intersection of Two Arrays
    • 58. Length of Last Word
    • 70. Climbing Stairs
    • 455. Assign Cookies
    • 83. Remove Duplicates from Sorted List
    • 160. Intersection of Two Linked Lists
    • 206. Reverse Linked List
    • 122. Best Time to Buy and Sell Stock II
    • 760. Find Anagram Mappings
    • 804. Unique Morse Code Words
    • 905. Sort Array By Parity
    • 852. Peak Index in a Mountain Array
    • 961. N-Repeated Element in Size 2N Array
    • 832. Flipping an Image
    • 617. Merge Two Binary Trees
    • 700. Search in a Binary Search Tree
    • 409. Longest Palindrome
    • 657. Robot Return to Origin
    • 942. DI String Match
    • 728. Self Dividing Numbers
    • 944. Delete Columns to Make Sorted
    • 509. Fibonacci Number
    • 1021. Remove Outermost Parentheses
    • 171. Excel Sheet Column Number
    • 999. Available Captures for Rook
    • 252. Meeting Rooms
    • 482. License Key Formatting
    • 844. Backspace String Compare
    • 938. Range Sum of BST
    • 557. Reverse Words in a String III
    • 922. Sort Array By Parity II
    • 559. Maximum Depth of N-ary Tree
    • 849. Maximize Distance to Closest Person
    • 463. Island Perimeter
    • 665. Non-decreasing Array
    • 53. Maximum Subarray
    • 448. Find All Numbers Disappeared in an Array
    • 141. Linked List Cycle
    • 937. Reorder Log Files
    • 303. Range Sum Query - Immutable
    • 1103. Distribute Candies to People
    • 202. Happy Number
    • 232. Implement Queue using Stacks
    • 1119. Remove Vowels from a String
    • 9. Palindrome Number
    • 266. Palindrome Permutation
    • 125. Valid Palindrome
    • 246. Strobogrammatic Number
    • 168. Excel Sheet Column Title
    • 38. Count and Say
    • 242. Valid Anagram
    • 290. Word Pattern
    • 293. Flip Game
    • 205. Isomorphic Strings
    • 345. Reverse Vowels of a String
    • 344. Reverse String
    • 383. Ransom Note
    • 387. First Unique Character in a String
    • 58. Length of Last Word
    • 14. Longest Common Prefix
    • 1122. Relative Sort Array
    • 219. Contains Duplicate II
    • 13. Roman to Integer
    • 169. Majority Element
    • 299. Bulls and Cows
    • 290. Word Pattern
    • 205. Isomorphic Strings
    • 744. Find Smallest Letter Greater Than Target
    • 763. Partition Labels
    • 110. Balanced Binary Tree
    • 543. Diameter of Binary Tree
    • 111. Minimum Depth of Binary Tree
    • 392. Is Subsequence
    • 20. Valid Parentheses
    • 7. Reverse Integer
    • 66. Plus One
    • 258. Add Digits
    • 67. Add Binary
    • 367. Valid Perfect Square
    • 204. Count Primes
    • 941. Valid Mountain Array
    • 100. Same Tree
    • 101. Symmetric Tree
    • 226. Invert Binary Tree
    • 257. Binary Tree Paths
    • 112. Path Sum
    • 113. Path Sum II
    • 104. Maximum Depth of Binary Tree
    • 111. Minimum Depth of Binary Tree
    • 110. Balanced Binary Tree
    • 107. Binary Tree Level Order Traversal II
    • 235. Lowest Common Ancestor of a Binary Search Tree
    • 256. Paint House
    • 1165. Single-Row Keyboard
    • 637. Average of Levels in Binary Tree
    • 141. Linked List Cycle
    • 276. Paint Fence
    • 237. Delete Node in a Linked List
    • 203. Remove Linked List Elements
    • 21. Merge Two Sorted Lists
    • 278. First Bad Version
    • 35. Search Insert Position
    • 349. Intersection of Two Arrays
    • 350. Intersection of Two Arrays II
    • 234. Palindrome Linked List
    • 937. Reorder Data in Log Files
    • 733. Flood Fill
    • 1114. Print in Order
    • 27. Remove Element
    • 339. Nested List Weight Sum
    • 155. Min Stack
    • 225. Implement Stack using Queues
    • 389. Find the Difference
    • 136. Single Number
    • 26. Remove Duplicates from Sorted Array
    • 80. Remove Duplicates from Sorted Array II
    • 189. Rotate Array
    • 572. Subtree of Another Tree
    • 359. Logger Rate Limiter
    • 346. Moving Average from Data Stream
    • 118. Pascal's Triangle
    • 119. Pascal's Triangle II
    • 217. Contains Duplicate
    • 243. Shortest Word Distance
    • 121. Best Time to Buy and Sell Stock
  • Medium
    • 621. Task Scheduler
    • 1823. Find the Winner of the Circular Game
    • 340. Longest Substring with At Most K Distinct Characters
    • 209. Minimum Size Subarray Sum
    • 142. Linked List Cycle II
    • 451. Sort Characters By Frequency
    • 503. Next Greater Element II
    • 807. Max Increase to Keep City Skyline
    • 285. Inorder Successor in BST
    • 395. Longest Substring with At Least K Repeating Characters
    • 12. Integer to Roman
    • 807. Max Increase to Keep City Skyline
    • 392. Is Subsequence
    • 763. Partition Labels
    • 1110. Delete Nodes And Return Forest
    • 1109. Corporate Flight Bookings
    • 370. Range Addition
    • 238. Product of Array Except Self
    • 3. Longest Substring Without Repeating Characters
    • 161. One Edit Distance
    • 249. Group Shifted Strings
    • 49. Group Anagrams
    • 6. ZigZag Conversion
    • 294. Flip Game II
    • 345. Reverse Vowels of a String
    • 151. Reverse Words in a String
    • 324. Wiggle Sort II
    • 215. Kth Largest Element in an Array
    • 280. Wiggle Sort
    • 56. Merge Intervals
    • 287. Find the Duplicate Number
    • 11. Container With Most Water
    • 271. Encode and Decode Strings
    • 5. Longest Palindromic Substring
    • 39. Combination Sum
    • 229. Majority Element II
    • 275. H-Index II
    • 244. Shortest Word Distance II
    • 55. Jump Game
    • 245. Shortest Word Distance III
    • 40. Combination Sum II
    • 216. Combination Sum III
    • 77. Combinations
    • 78. Subsets
    • 90. Subsets II
    • 131. Palindrome Partitioning
    • 17. Letter Combinations of a Phone Number
    • 739. Daily Temperatures
    • 46. Permutations
    • 49. Group Anagrams
    • 253. Meeting Rooms II
    • 540. Single Element in a Sorted Array
    • 267. Palindrome Permutation II
    • 187. Repeated DNA Sequences
    • 165. Compare Version Numbers
    • 43. Multiply Strings
    • 144. Binary Tree Preorder Traversal
    • 94. Binary Tree Inorder Traversal
    • 102. Binary Tree Level Order Traversal
    • 129. Sum Root to Leaf Numbers
    • 298. Binary Tree Longest Consecutive Sequence
    • 337. House Robber III
    • 103. Binary Tree Zigzag Level Order Traversal
    • 199. Binary Tree Right Side View
    • 1169. Invalid Transactions
    • 98. Validate Binary Search Tree
    • 236. Lowest Common Ancestor of a Binary Tree
    • 254. Factor Combinations
    • 47. Permutations II
    • 31. Next Permutation
    • 60. Permutation Sequence
    • 62. Unique Paths
    • 63. Unique Paths II
    • 279. Perfect Squares
    • 139. Word Break
    • 322. Coin Change
    • 64. Minimum Path Sum
    • 221. Maximal Square
    • 24. Swap Nodes in Pairs
    • 328. Odd Even Linked List
    • 92. Reverse Linked List II
    • 120. Triangle
    • 82. Remove Duplicates from Sorted List II
    • 2. Add Two Numbers
    • 33. Search in Rotated Sorted Array
    • 81. Search in Rotated Sorted Array II
    • 153. Find Minimum in Rotated Sorted Array
    • 162. Find Peak Element
    • 374. Guess Number Higher or Lower
    • 34. Find First and Last Position of Element in Sorted Array
    • 300. Longest Increasing Subsequence
    • 48. Rotate Image
    • 54. Spiral Matrix
    • 59. Spiral Matrix II
    • 73. Set Matrix Zeroes
    • 311. Sparse Matrix Multiplication
    • 74. Search a 2D Matrix
    • 240. Search a 2D Matrix II
    • 370. Range Addition
    • 79. Word Search
    • 200. Number of Islands
    • 994. Rotting Oranges
    • 286. Walls and Gates
    • 323. Number of Connected Components in an Undirected Graph
    • 130. Surrounded Regions
    • 60. Permutation Sequence
    • 127. Word Ladder
    • 79. Word Search
    • 364. Nested List Weight Sum II
    • 150. Evaluate Reverse Polish Notation
    • 394. Decode String
    • 347. Top K Frequent Elements
    • 332. Reconstruct Itinerary
    • 341. Flatten Nested List Iterator
    • 318. Maximum Product of Word Lengths
    • 207. Course Schedule
    • 210. Course Schedule II
    • 384. Shuffle an Array
    • 277. Find the Celebrity
    • 133. Clone Graph
    • 399. Evaluate Division
    • 356. Line Reflection
    • 310. Minimum Height Trees
    • 223. Rectangle Area
    • 261. Graph Valid Tree
    • 211. Add and Search Word - Data structure design
    • 208. Implement Trie (Prefix Tree)
    • 362. Design Hit Counter
    • 281. Zigzag Iterator
    • 8. String to Integer (atoi)
    • 15. 3Sum
    • 18. 4Sum
    • 134. Gas Station
    • 981. Time Based Key-Value Store
    • 1007. Minimum Domino Rotations For Equal Row
    • 1057. Campus Bikes
    • 309. Best Time to Buy and Sell Stock with Cooldown
  • Hard
    • 4. Median of Two Sorted Arrays
    • 188. Best Time to Buy and Sell Stock IV
    • 123. Best Time to Buy and Sell Stock III
    • 145. Binary Tree Postorder Traversal
    • 265. Paint House II
    • 154. Find Minimum in Rotated Sorted Array II
    • 315. Count of Smaller Numbers After Self
    • 305. Number of Islands II
    • 42. Trapping Rain Water
    • 45. Jump Game II
Powered by GitBook
On this page

Was this helpful?

  1. Medium

210. Course Schedule II

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Example 1:

Input: 2, [[1,0]] 
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished   
             course 0. So the correct course order is [0,1] .

Example 2:

Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both     
             courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. 
             So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] .

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

  2. You may assume that there are no duplicate edges in the input prerequisites.

解题要点:

与上一题想法类似,不同的是,在queue里处理的每个元素都加进返回值里,如果返回值不足课程数量,说明满足不了上完全部的课,返回空,除此之外直接返回最终值。

class Solution(object):
    def findOrder(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: List[int]
        """
        res = []
        indegrees = [0] * numCourses
        mydict = collections.defaultdict(list)
        for i in range(len(prerequisites)):
            indegrees[prerequisites[i][0]] += 1
            mydict[prerequisites[i][1]] += prerequisites[i][0],
        
        queue = []
        for n in range(numCourses):
            if indegrees[n] == 0:
                queue.append(n)
        
        while queue: 
            p = queue.pop(0)
            res.append(p)       
            for e in mydict[p]:
                indegrees[e] -= 1
                if indegrees[e] == 0:
                    queue.append(e)
        if len(res) == numCourses:
            return res
        else:
            return []
Previous207. Course ScheduleNext384. Shuffle an Array

Last updated 5 years ago

Was this helpful?