【leetcode】顏色分類-java

題目描述

給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。

此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。

注意:
不能使用代碼庫中的排序函數來解決這道題。

示例:

輸入: [2,0,2,1,1,0]
輸出: [0,0,1,1,2,2]
進階:

一個直觀的解決方案是使用計數排序的兩趟掃描算法。
首先,迭代計算出0、1 和 2 元素的個數,然後按照0、1、2的排序,重寫當前數組。
你能想出一個僅使用常數空間的一趟掃描算法嗎?

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/sort-colors
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

代碼實現

class Solution {
    public void sortColors(int[] nums) {
        int redCount = 0,writeCount=0,blueCount=0;
        //
    	for(int n=0;n<nums.length;n++){
    		if(nums[n] == 0){
    			redCount++;
    		}else if(nums[n] == 1 ){
    			writeCount++;
    		}else{
    			blueCount++;
    		}
    		
    	}
    	
    	for(int i=0;i<redCount;i++){
    		nums[i] = 0;
    	}
    	
    	for(int i=redCount;i<redCount+writeCount;i++){
    		nums[i] = 1 ;
    	}
    	
    	for(int i=redCount+writeCount;i<redCount+writeCount+blueCount;i++){
    		nums[i] = 2;
    	}
    	
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章