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 }
  • 相关阅读:
    CompareUtil
    linux awk学习笔记
    linux用grep查找包含两个关键字的命令
    mysql 使用set names 解决乱码问题
    对私有静态方法进行单测
    使用JUnit测试预期异常
    Tortoise svn 冲突解决主要办法
    tortoise svn冲突解决
    word-break与word-wrap
    移动端适配
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4802374.html
Copyright © 2011-2022 走看看