Medium 75题 Sort Colors
2016-09-24 13:33
330 查看
Question:
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:
思路很容易想到,put all the 0 in the front and 2 in the the back... but there are several places we should pay attention to...
we should re-check the number after swap.
9/30 第二次看了discussion,由于从前往后遍历,循环有顺序问题,因为第一个循环有可能交换过来一个0,要么就破坏了
int n=nums.length;
int zero=0;
int two=n-1;
for(int i=0;i<=two;i++)
{
while(nums[i]==2&&i<two)
{
//swap(nums[i],nums[two--])
int tmp=nums[i];
nums[i]=nums[two];
nums[two]=tmp;
two--;
}
while(nums[i]==0&&i>zero)
{
//swap(nums[i],nums[zero++]);
int tmp=nums[i];
nums[i]=nums[zero];
nums[zero]=tmp;
zero++;
}
}
}
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:
思路很容易想到,put all the 0 in the front and 2 in the the back... but there are several places we should pay attention to...
we should re-check the number after swap.
public class Solution { public void sortColors(int[] nums) { int n=nums.length; int first=0; int last=n-1; for(int i=0;i<=n-1&&last!=0&&first!=n-1&&first!=last;i++) { if(nums[i]==2) { if(i<last) { int tmp=nums[i]; nums[i]=nums[last]; nums[last]=tmp; last--; i--; } else if(i==last) { last--; } continue; } if(nums[i]==0) { if(i>first) { int tmp=nums[i]; nums[i]=nums[first]; nums[first]=tmp; first++; i--; } else if(i==first) { first++; } continue; } } } }
9/30 第二次看了discussion,由于从前往后遍历,循环有顺序问题,因为第一个循环有可能交换过来一个0,要么就破坏了
int n=nums.length;
int zero=0;
int two=n-1;
for(int i=0;i<=two;i++)
{
while(nums[i]==2&&i<two)
{
//swap(nums[i],nums[two--])
int tmp=nums[i];
nums[i]=nums[two];
nums[two]=tmp;
two--;
}
while(nums[i]==0&&i>zero)
{
//swap(nums[i],nums[zero++]);
int tmp=nums[i];
nums[i]=nums[zero];
nums[zero]=tmp;
zero++;
}
}
}
相关文章推荐
- Leetcode 75. Sort Colors (Medium) (cpp)
- 75. Sort Colors 难度:medium
- LeetCode-75-Sort Colors(双指针)-Medium
- 【Medium】75. Sort Colors
- 【Leet Code】 75.Sort Colors--medium
- 【LeetCode】75.Sort Colors(Medium)解题报告
- leetcode_question_75 Sort Colors
- [LeetCode] 75. Sort Colors
- [Leetcode] #75 Sort Colors
- 75. Sort Colors
- [leetcode]75. Sort Colors
- [leetCode 75] Sort Colors
- 75. Sort Colors
- [LeetCode]75. Sort Colors
- LeetCode 75 Sort Colors
- [leetcode 75] Sort Colors-----------只有三种颜色的排序
- 75. Sort Colors
- 75. Sort Colors
- 75. Sort Colors
- [leetcode] 【排序】 75. Sort Colors