Sort Colors

mac2022-06-30  67

 

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.

 

1 public class Solution { 2 public void sortColors(int[] nums) 3 { 4 int len = nums.length; 5 if(nums==null||nums.length<=1)return; 6 7 int left = 0; 8 int right = len-1; 9 int i = 0; 10 while(i<=right) 11 { 12 if(nums[i]==0) 13 { 14 swap(nums,left,i); 15 left++; 16 i++; 17 } 18 else if(nums[i]==1) 19 { 20 i++; 21 } 22 else 23 { 24 swap(nums,right,i); 25 right--; 26 //i++; 27 } 28 } 29 30 return; 31 32 } 33 34 public void swap (int[] nums, int p, int i) 35 { 36 int temp = nums[p]; 37 nums[p]=nums[i]; 38 nums[i]=temp; 39 } 40 }

 

转载于:https://www.cnblogs.com/hygeia/p/4897430.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)