Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Leetcode 题解 - 排序.md #1183

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 26 additions & 15 deletions notes/Leetcode 题解 - 排序.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,21 +224,32 @@ Output: [0,0,1,1,2,2]

```java
public void sortColors(int[] nums) {
int zero = -1, one = 0, two = nums.length;
while (one < two) {
if (nums[one] == 0) {
swap(nums, ++zero, one++);
} else if (nums[one] == 2) {
swap(nums, --two, one);
} else {
++one;
int p0=0;
int p1=0;
for(int i=0;i<nums.length;i++)
{
if(nums[i]==1)
{
int temp=nums[i];
nums[i]=nums[p1];
nums[p1]=temp;
p1++;
}
else if(nums[i]==0)
{
int temp=nums[i];
nums[i]=nums[p0];
nums[p0]=temp;
if(p0<p1)
{
int k=nums[i];
nums[i]=nums[p1];
nums[p1]=k;

}
p0++;
p1++;
}
}
}
}

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