赞
踩
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.
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Input: nums = [2,0,1]
Output: [0,1,2]
From: LeetCode
Link: 75. Sort Colors
1. Initialization: Three pointers are used, low, mid, and high, which initially point to the beginning of the array, the beginning of the array, and the end of the array, respectively.
2. Iterative Processing: The mid pointer is used to iterate over the array. For each element at mid:
3. Termination: The process continues until mid exceeds high. At this point, all 0s are to the left of low, all 2s are to the right of high, and 1s are naturally between low and high.
void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } void sortColors(int* nums, int numsSize) { int low = 0, mid = 0, high = numsSize - 1; while (mid <= high) { switch (nums[mid]) { case 0: // Red swap(&nums[low++], &nums[mid++]); break; case 1: // White mid++; break; case 2: // Blue swap(&nums[mid], &nums[high--]); break; } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。