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

    https://leetcode.com/problems/sort-colors/description/
    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.


     1 public void sortColors(int[] nums) {
     2         /*
     3         this is rainbow sort:
     4         (-inf, i) val = 0  swap i++ j++
     5         [i,j) val = 1       no swap  j++
     6         (k, +inf) val = 2    swap, k--
     7         [j, k] unknown area
     8         use the j as counter
     9         * */
    10         if (nums == null || nums.length ==0) return;
    11         int i =0 , j = 0, k = nums.length-1 ;
    12         while (j<=k){
    13             if (nums[j] == 0 ){
    14                 swap(nums, i, j);
    15                 i++;
    16                 j++;
    17             }else if(nums[j] == 1){
    18                 j++;
    19             } else{
    20                 swap(nums,j,k);
    21                 k--;
    22             }
    23         }
    24     }
    25     private void swap(int[] nums, int left, int right){
    26         int temp = nums[left];
    27         nums[left] = nums[right];
    28         nums[right] = temp ;
    29     }
  • 相关阅读:
    iOS优化内存方法推荐
    Swift和OC,是编译型语言、解释性语言、运行时语言
    redis常用命令
    redis 基本类型
    spring中事务配置
    redis 基本概览
    ThreadLocal 类说明
    spring 中 AOP 功能
    ps抠图简单方法
    nginx配置文件中location说明
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8553324.html
Copyright © 2011-2022 走看看