码迷,mamicode.com
首页 > 其他好文 > 详细

[Algo] 11. Rainbow Sort

时间:2020-03-04 09:17:30      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:--   ++   anything   ==   examples   put   else   sum   not   

Given an array of balls, where the color of the balls can only be Red, Green or Blue, sort the balls such that all the Red balls are grouped on the left side, all the Green balls are grouped in the middle and all the Blue balls are grouped on the right side. (Red is denoted by -1, Green is denoted by 0, and Blue is denoted by 1).

Examples

  • {0} is sorted to {0}
  • {1, 0} is sorted to {0, 1}
  • {1, 0, 1, -1, 0} is sorted to {-1, 0, 0, 1, 1}

Assumptions

  • The input array is not null.

Corner Cases

  • What if the input array is of length zero? In this case, we should not do anything as well.
public class Solution {
  public int[] rainbowSort(int[] array) {
    // Write your solution here
    if (array == null || array.length == 0) {
      return array;
    }
    int neg = 0;
    int pos = array.length - 1;
    int zero = 0;
    while (zero <= pos) {
        if (array[zero] == -1) {
          swap(array, zero++, neg++);
        } else if (array[zero] == 0) {
          zero++;
        } else {
          swap(array, zero, pos--);
        }
    }
    return array;
  }

  private void swap (int[] arr, int a, int b) {
      int tmp = arr[a];
      arr[a] = arr[b];
      arr[b] = tmp;
  }
}

 

[Algo] 11. Rainbow Sort

标签:--   ++   anything   ==   examples   put   else   sum   not   

原文地址:https://www.cnblogs.com/xuanlu/p/12406046.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!