LeetCode第75題

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

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

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

示例:

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

思路:這個題採用計數排序就可以解決。

	public void sortColors(int[] nums){
		for(int i=nums.length-1;i>=0;i--){
			for(int j=0;j<nums.length-1;j++){
				if(nums[j]>nums[j+1]){
					int temp=nums[j];
					nums[j]=nums[j+1];
					nums[j+1]=temp;
				}
			}
		}
		
	}

網上有好多采用三路快排的方法解決的,代碼如下。

public static void sortColors(int[] nums){
    	int low=0,high=nums.length-1;
    	int i=0;
    	while(i<=high){
    		if(nums[i]==0){
    			int temp=nums[low];
    			nums[low]=nums[i];
    			nums[i]=temp;
    			++i;++low;
    		}
    		else if(nums[i]==1){
    			++i;
    		}
    		else if(nums[i]==2){
    			int temp=nums[i];
    			nums[i]=nums[high];
    			nums[high]=temp;
    			--high;
    		}
    	}

 

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