Sort Colors

Given an array withnobjects 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.

分析

这个题试试不用0, 1, 2 写,而是call API 的方式

热身题,不解释,摆码

思考为何要 ++front 不能 front++? 为何 --back 不能 back -- ?

代码

class Solution {
        public void sortColors(int[] nums){
            int front = -1; 
            int back = nums.length;
            int i = 0;
            while( i < back){
                int result = api(nums[i]);
                if(result < 0){
                    swap(nums, ++front, i++);
                }else if(result == 0){
                    i++;
                }else{
                    swap(nums, --back, i );
                }
            }  
        }

        private int api(int num) {
            if (num == 0) {
                return new Random().nextInt(50) * -1 - 1; // -1
            } else if (num == 1) {
                return 0; // = 
            } else {
                return new Random().nextInt(100) + 1; // 1
            }
     }

        private void swap(int[] nums, int m , int n){
            int temp = nums[m];
            nums[m] = nums[n];
            nums[n] = temp;
      }   
}

results matching ""

    No results matching ""