您的位置:首页 > 其它

75. Sort Colors

2017-06-11 20:35 197 查看
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.

思路:这题要实现的是将所有的0放到数组的左边,将所有的2放到数组的右边,采取快速排序的思想,将2都交换到数组的后面,将0都交换到数组的前面,具体代码如下:

public void sortColors(int[] nums) {
if (nums.length==0||nums.length==1) return;
int end=nums.length-1;
int beign=0;
for (int i = 0; i <=end; i++) {
while (nums[i]==2&i<end) {
int temp=nums[i];
nums[i]=nums[end];
nums[end--]=temp;
}
while (nums[i]==0&&i>beign){
int temp=nums[i];
nums[i]=nums[beign];
nums[beign++]=temp;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: