To the Top
File:  root - text - article - 2019 - 12 - sort-colors.txt.txt
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 520 Views, 14372 Search Bots | 118 Words

Subscribe to Feed Burner | Browse | Archive
Hi, here's your problem today. This problem was recently asked by Apple:

Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library’s sort function for this problem.

Can you do this in a single pass?

Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Here's a starting point:


class Solution:
def sortColors(self, nums):
# Fill this in.

nums = [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1]
print("Before Sort: ")
print(nums)
# [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1]

Solution().sortColors(nums)
print("After Sort: ")
print(nums)
# [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2]
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Cateogry: Computing | 520 Views, 14372 Search Bots | 118 Words Subscribe to Feed Burner

Related Articles

  1. Daily Interview Puzzle: Ways to Traverse a Grid
  2. Algorithm Interview: Lowest Common Ancestor of 2 Nodes in Binary Tree
  3. Invert a Binary Tree
  4. Daily Interview Problem: Circle of Chained Words
  5. Daily Interview Problem:Create a balanced binary search tree
  6. Reverse a Directed Graph
  7. Daily Interview Problem: Reconstrunct Binary Tree from Preorder and Inorder Traversals
  8. Most Frequent Subtree Sum
  9. Reverse a Linked List
  10. Windows Scripting

Comments (0)

Your Email (Domain Part Not Exposed):

Your Comments:

Privately By Mail Colors More Smileys S x y @

Verification (Click Image 2 Refresh):

    Be the first one to comment this page !


Page Edited: October 30 2020 14:21:09 | RSS Subscription
How to Cook a Perfect Steak? | <meta name="robots" content="noindex, follow" />