LeetCode每日一題:sort colors
問題描述
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.
click to show follow up.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
問題分析
這道題簡單的解法題目都規定不能使用,不能呼叫庫函式sort,不能採用迴圈兩遍的複寫A演算法,這道題只能遍歷一遍。
設三個指標,left表示從左往右第一個1的數,right表示從右往左第一個不是2的數,i從0開始向最末尾前進,遇到0,就與left交換,遇到2就與right交換,這樣一趟走下來就是有序的了。
程式碼實現
public void sortColors(int[] A) {
int left = 0;
int right = A.length - 1;
int i = 0;
while (i <= right) {
if (A[i] == 0) {
swap(A, left, i);
left++;
i++;
} else if (A[i] == 2) {
swap(A, i, right);
right--;
} else i++;
}
}
private void swap(int[] A, int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
相關文章
- 75. Sort Colors(Leetcode每日一題-2020.10.07)LeetCode每日一題
- Leetcode Sort ColorsLeetCode
- Leetcode每日一題:992.sort-array-by-parity-ii(按奇偶排序陣列Ⅱ)LeetCode每日一題排序陣列
- leetcode每日一題LeetCode每日一題
- Leetcode每日一題(1)LeetCode每日一題
- LeetCode 2024/6 每日一題 合集LeetCode每日一題
- LeetCode 每日一題「判定字元是否唯一」LeetCode每日一題字元
- LeetCode每日一題: 找不同(No.389)LeetCode每日一題
- LeetCode每日一題: 移除元素(No.27)LeetCode每日一題
- Leetcode Sort ArrayLeetCode
- LeetCode每日一題: 排列硬幣(No.441)LeetCode每日一題
- LeetCode每日一題: 各位相加(No.258)LeetCode每日一題
- 【LeetCode】每日一題164. 最大間距LeetCode每日一題
- LeetCode每日一題: 移動零(No.283)LeetCode每日一題
- LeetCode每日一題:迴文數(No.9)LeetCode每日一題
- LeetCode每日一題:兩數之和(No.1)LeetCode每日一題
- LeetCode每日一題:自除數(No.728)LeetCode每日一題
- LeetCode每日一題:Nim遊戲(No.292)LeetCode每日一題遊戲
- LeetCode每日一題:求眾數(No.169)LeetCode每日一題
- LeetCode每日一題:爬樓梯(No.70)LeetCode每日一題
- Leetcode每日一題:面試題16.19.水域大小LeetCode每日一題面試題
- leetcode每日一題刷題記錄(10.26-10.30)LeetCode每日一題
- 【js】Leetcode每日一題-葉子相似的樹JSLeetCode每日一題
- 【leetcode】(每日一題 771 寶石與石頭)LeetCode每日一題
- LeetCode每日一題 (32)1. 兩數之和LeetCode每日一題
- 【每日一題-leetcode】416. 分割等和子集每日一題LeetCode
- 18. 4Sum(Leetcode每日一題-2020.10.05)LeetCode每日一題
- LeetCode每日一題: 旋轉陣列(No.189)LeetCode每日一題陣列
- LeetCode每日一題: 猜數字大小(No.374)LeetCode每日一題
- LeetCode每日一題: 搜尋插入位置(No.35)LeetCode每日一題
- LeetCode每日一題: 轉置矩陣(No.867)LeetCode每日一題矩陣
- 135. Candy(Leetcode每日一題-2020.12.24)--抄答案LeetCode每日一題
- LeetCode:每日一題:27. 移除元素 ——————簡單LeetCode每日一題
- 2020年12月4日leetcode每日一題LeetCode每日一題
- 976. Largest Perimeter Triangle(Leetcode每日一題-2020.11.29)LeetCode每日一題
- LeetCode每日一題:整數反轉(No.7)LeetCode每日一題
- LeetCode每日一題: 路徑總和(No.112)LeetCode每日一題
- LeetCode每日一題:最長公共字首(No.14)LeetCode每日一題
- Leetcode每日一題:52.N-Queens II(N皇后Ⅱ)LeetCode每日一題