Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8a4e288

Browse files
Sort-colors
1 parent 1e4b403 commit 8a4e288

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

‎Two-pointers/difficult/sort-colors.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"Leetcode- https://leetcode.com/problems/sort-colors/ "
2+
'''
3+
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
4+
5+
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
6+
7+
You must solve this problem without using the library's sort function.
8+
9+
Example 1:
10+
11+
Input: nums = [2,0,2,1,1,0]
12+
Output: [0,0,1,1,2,2]
13+
'''
14+
def sortColors(self, nums):
15+
l=0
16+
r=len(nums)-1
17+
m=0
18+
19+
while m<=r:
20+
if nums[m]==0:
21+
nums[m],nums[l]=nums[l],nums[m]
22+
l+=1
23+
m+=1
24+
elif nums[m]==2:
25+
nums[m],nums[r]=nums[r],nums[m]
26+
r-=1
27+
else:
28+
m+=1
29+
return nums
30+
31+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /