您的位置:首页 > 其它

75. Sort Colors

2015-04-18 11:54 176 查看
题目:

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.

链接: http://leetcode.com/problems/sort-colors/

题解: 排序0, 1和2,把0交换到数组头,2交换到数组末尾,1不变。这题在Microsoft的OA里做到过。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {
public void sortColors(int[] A) {
if(A == null || A.length == 0)
return;
int index = 0, left = 0 , right = A.length - 1;

while(index <= right){
if(A[index] == 0){
swap(A, index ++, left ++);
} else if (A[index] == 1)
index ++;
else
swap(A, index, right --);
}

}

private void swap(int[] A, int m , int n){
int temp = A[m];
A[m] = A
;
A
= temp;
}
}


Update

public class Solution {
public void sortColors(int[] nums) {
if(nums == null || nums.length == 0)
return false;
int lo = 0, hi = nums.length - 1;
int index = 0;

while(index <= hi) {
if(nums[index] == 0)
swap(nums, index++, lo++);
else if(nums[index] == 2)
swap(nums, index, hi--);
else
index++;
}
}

private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}


二刷:

我们可以借用一个swap函数,来把这三种情况进行排序。

首先设定一个lo = 0, hi = nums.length - 1, 另外设置一个用来遍历的指针index = 0

当index <= hi的情况下
假如 nums[index] = 0, 那么我们把index这个位置元素换到数组头部去, swap(nums, index++, lo++)

假如nums[index] = 2, 那么我们把index这个位置的元素换到数组尾部,swap(nums, index, hi--), 这里因为我们不确定新换过来的元素的值,所以index这个位置还需要重新判定

否则nums[index] = 1,我们增加index++, 继续判断下一个元素。

最后返回结果。

Java:

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {
public void sortColors(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int lo = 0, hi = nums.length - 1;
int index = 0;
while (index <= hi) {
if (nums[index] == 0) {
swap(nums, index++, lo++);
} else if (nums[index] == 2) {
swap(nums, index, hi--);
} else {
index++;
}
}
}

private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}


题外话:

2/4/2016

今天偶尔听到了姚贝娜唱的<鱼>,然后就一直悲伤了一晚。现在最大的感受是 - 人要好好生活,每天努力,快乐。

三刷:

Java:

public class Solution {
public void sortColors(int[] nums) {
if (nums == null || nums.length < 2) return;
int lo = 0, hi = nums.length - 1, index = 0;
while (index <= hi) {
if (nums[index] == 0) swap(nums, index++, lo++);
else if (nums[index] == 2) swap(nums, index, hi--);
else index++;
}
}

private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}


测试:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: