【LeetCode】75.Sort Colors(Medium)解题报告
题目地址:https://leetcode.com/problems/sort-colors/description/
题目描述:
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.
Solution:
// 1 2 0 1
// 0 1 1 2
//time : O(n)
//space : O(1)
class Solution {
public void sortColors(int[] nums) {
int left = 0;
int right = nums.length - 1;
int index = 0;
while(index <= right){
if(nums[index] == 0){
swap(nums,index++,left++);
}else if(nums[index] == 2){
swap(nums,index,right--);
}else{
index++;
}
}
}
public void swap(int[] nums,int a,int b){
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}
Date:2018年2月23日