zoukankan      html  css  js  c++  java
  • 75. Sort Colors

    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.

    给定一个包含红,白,蓝且长度为n的数组,将数组元素进行分类使同颜色的元素相邻,并按照红、白、蓝的顺序进行排序。
    我们可以使用整数0,1和2分别代表红,白,蓝。

     1     private void swap(int[] nums,int left,int right)
     2     {
     3         int temp = nums[left];
     4         nums[left] = nums[right];
     5         nums[right] = temp;
     6     }
     7     
     8     public void sortColors(int[] nums) {
     9         int second=nums.length-1, zero=0;
    10         for (int i=0; i<=second; i++) {
    11             while (nums[i]==2 && i<second) swap(nums,i,second--);
    12             while (nums[i]==0 && i>zero) swap(nums,i,zero++);
    13         }  
    14     }
  • 相关阅读:
    c#配置文件
    C#预处理指令
    C#面向对象详解
    231. Power of Two
    226. Invert Binary Tree
    C语言函数入参压栈顺序为什么是从右向左?
    对C++ 虚函数的理解
    悲观锁和乐观锁
    什么是索引
    CHAR 和VARCHAR的区别
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7676028.html
Copyright © 2011-2022 走看看