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.

用0,1,2,分別代表紅色,白色和藍色,按照紅白藍的順序排序,並且相同的顏色要相鄰,所以這道題是對一個含有0,1,2三個元素的數組排序即可,但是不能調用排序函數Arrays.sort(),所以需要掃描兩遍數組,第一次計數,記錄每個數字出現的次數,第二次給數組賦值,代碼如下:

if(nums.length<2){return;}
    	int count0=0,count1=0,count2=0;
        for(int i=0;i<nums.length;i++){
        	if(nums[i]==0){count0++;}
        	if(nums[i]==1){count1++;}
        	if(nums[i]==2){count2++;}
        	
        }
       
        for(int j = 0;j<count0;j++){
        	nums[j]=0;
        }
        for(int k = 0;k<count1;k++){
        	nums[k+count0]=1;
        }
        for(int l=0;l<count2;l++){
        	nums[l+count0+count1]=2;
        }
但是這種寫法效率很低==在網上找了另一種方法,直接平移,當數組中的數字爲0,時,數組中的0,1,2都向後平移一位,當數字爲1時,1和2向後移動一位,數字爲2時,僅2向後移一位,雖然這種方法效率也不高==但是隻對數組掃描了一遍,代碼如下:

int len = nums.length;
		int j=-1,k=-1,n=-1;
		for(int i=0;i<len;i++){
			if(nums[i]==0){
				nums[++n]=2;
				nums[++k]=1;
				nums[++j]=0;
			}
			else if(nums[i]==1){
				nums[++n]=2;
				nums[++k]=1;
			}
			else{
				nums[++n]=2;
			}
		}



發佈了64 篇原創文章 · 獲贊 9 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章