zoukankan      html  css  js  c++  java
  • Sort Colors 解答

    Question

    Given an array with n objects colored red, white or blue, sort them 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.

    Solution 1 -- Counting Sort

    Straight way, time complexity O(n), space cost O(1)

     1 public class Solution {
     2     public void sortColors(int[] nums) {
     3         int[] count = new int[3];
     4         int length = nums.length;
     5         for (int i = 0; i < length; i++)
     6             count[nums[i]]++;    
     7         for (int i = 0; i < count[0]; i++)
     8             nums[i] = 0;
     9         for (int i = 0; i < count[1]; i++)
    10             nums[i + count[0]] = 1;
    11         for (int i = 0; i < count[2]; i++)
    12             nums[i + count[0] + count[1]] = 2;
    13     }
    14 }

    Solution 2 -- Two Pointers

    We can use two pointers here to represent current red position and blue position. redIndex starts from 0, and blueIndex starts from length - 1.

    We traverse once from 0 to blueIndex.

    Each time we find nums[i] is not 1:

    if nums[i] is 0, we move it to redIndex position

    if nums[i] is 2, we move it to blueIndex position

    Time complexity O(n), space cost O(1) 

     1 public class Solution {
     2     public void sortColors(int[] nums) {
     3         int length = nums.length;
     4         int redIndex = 0, blueIndex = length - 1, i = 0;
     5         while (i <= blueIndex) {
     6             // If current color is red, we need to switch it to red position
     7             if (nums[i] == 0) {
     8                 // Switch nums[i] with nums[redIndex]
     9                 nums[i] = nums[redIndex];
    10                 nums[redIndex] = 0;
    11                 redIndex++;
    12                 i++;
    13             } else if (nums[i] == 2) {
    14                 // If current color is blue, we need to switch it to blue position and check switched color
    15                 // Switch nums[i] with nums[blueIndex]
    16                 nums[i] = nums[blueIndex];
    17                 nums[blueIndex] = 2;
    18                 blueIndex--;
    19             } else {
    20                 i++;
    21             }
    22         }
    23     }
    24 }
  • 相关阅读:
    The Django Book学习笔记 04 模板
    The Django Book学习笔记
    Python标准库 datetime
    Python %s和%r的区别
    Python转载
    Python while 1 和 while True 速度比较
    Git 时光穿梭鸡 删除文件 以及批量删除文件
    git reset soft,hard,mixed之区别深解
    Git 时光穿梭鸡 撤销修改
    Git 时光穿梭鸡 管理修改
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4802374.html
Copyright © 2011-2022 走看看