LeetCode--sortColor

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.

题目:按数字大小来排序~
public class Solution { public void sortColors(int[] nums) { if (nums==null || nums.length<2) { return; } int i=0, j=0, k=nums.length-1; while (j <= k) { if (nums[j] == 0) { swap(nums, i++, j++); } // should swap with whatever at index i; note that i++ AND j++ else if (nums[j] == 1) { ++j; } else { swap(nums, j, k--); } // nums[j]==2, should swap with whatever at index k, then --k } } private void swap(int[] nums, int i, int j) { int save = nums[i]; nums[i] = nums[j]; nums[j] = save; } }

我的。。。只顾简单了
package leetcode;

public class SortColor {

    public void SortClor(int[] array){
        int c0=0;
        int c1=0;
        int c2=0;
        if(array.length<1) System.out.println("请输入正确的数组!");
        if(array==null) System.out.println("输入的数组无效!");
        for(int i = 0;i<array.length;i++){
            if(array[i]==0)  c0++;
            if(array[i]==1)  c1++;
            c2++;
        }
        for(int i = 0 ;i<array.length;i++) {
            if(i<c0) array[i] = 0;
            if(i>c0&&i<c0+c1) array[i] = 1;
            if(i>=c0+c1) array[i] = 2;
        }
        
        
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}


注意:1、java中的 i++和++i
{int i=0; int j=i++;}
{int i=0; int z=++i;}
运算过后,j=0;表明i++是指先把i赋值给j然后再自身加1;
运算过后,z=1;表明++i是指先自身加1后赋值给z;
总之记住++号在后面的意思是先赋值然后自身加1;++在前面的是先自身加1后赋值;
2、当题目简单时,想想可以优化吗?用更少的时间or空间复杂度?能否直接在原来数组操作?能否只在遍历一次的时候就给操作了?
态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
原文地址:https://www.cnblogs.com/neversayno/p/5275687.html