• 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 }
  • 相关阅读:
    Linux下zip命令使用
    docker镜像发布到阿里云镜像仓库
    基于官方镜像定制php-fpm容器
    docker-compose部署开发环境
    docker安装discuz!Q
    从零开始实现简单 RPC 框架 4:注册中心
    从零开始实现简单 RPC 框架 3:配置总线 URL
    从零开始实现简单 RPC 框架 2:扩展利器 SPI
    从零开始实现简单 RPC 框架 1:RPC 框架的结构和设计
    文本分类(六):pytorch实现DPCNN
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4802374.html
Copyright © 2020-2023  润新知