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.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
Example 3:
Input: nums = [0]
Output: [0]
Example 4:
Input: nums = [1]
Output: [1]
Constraints:
由頭(i)和尾(j)開始兩兩比較,
j由後向前和i比較,
若j較i小,則ij交換
j全部比完後,則將向後移
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
i=0
for i in range(n):
for j in range(n-1,i,-1):
while j>i and nums[j] < nums[i]:
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
Cool!
用swap的方式 做排序
把第一小,第二小...最後一個依序換到最前方來完成排序.
我好久沒實作排序啦,都直接alist.sort(),但這題不行直接
call sort.
Try Try this.(mark 兩行)(我還沒驗證)
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
#i=0
for i in range(n):
for j in range(n-1,i,-1):
while nums[j] < nums[i]: #
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
我剛剛試了
這樣子打美得斯哈哈哈
我使用swap的方式,我的i前面一定都是比他小的數字,所以要一個j>i的判斷式,避免他重複比較已經排好的