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, 14113 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, 14113 Search Bots | 118 Words Subscribe to Feed Burner

Related Articles

  1. YES!!
  2. Reverse a Directed Graph
  3. Daily Interview Problem: Buddy Strings
  4. Print a tree level-by-level, with line-breaks
  5. 56 Bytes
  6. Daily Interview Problem: Count Number of Unival Subtrees
  7. Top K Frequent words
  8. Daily Interview Problem:Create a balanced binary search tree
  9. Multitasking
  10. Find Pythagorean Triplets

Comments (0)

    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="index, follow">