75. Sort Colors(Leetcode每日一題-2020.10.07)
Problem
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.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Constraints:
- n == nums.length
- 1 <= n <= 300
- nums[i] is 0, 1, or 2.
Follow up:
- Could you solve this problem without using the library’s sort function?
- Could you come up with a one-pass algorithm using only O(1) constant space?
Example1
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example2
Input: nums = [2,0,1]
Output: [0,1,2]
Example3
Input: nums = [0]
Output: [0]
Example4
Input: nums = [1]
Output: [1]
Solution
class Solution {
public:
void sortColors(vector<int>& nums) {
int i = 0;
int j = 0;
int k = nums.size() - 1;
while(i <= k)
{
if(nums[i] == 0)
{
swap(nums[i++],nums[j++]);
}
else if(nums[i] == 1)
{
++i;
}
else{
swap(nums[i],nums[k--]);
}
}
}
};
相關文章
- LeetCode每日一題:sort colorsLeetCode每日一題
- 75. Sort Colors:計數排序排序
- Leetcode Sort ColorsLeetCode
- Leetcode-Sort ColorsLeetCode
- Sort Colors leetcode javaLeetCodeJava
- 【LeetCode】Sort Colors 陣列排序LeetCode陣列排序
- LintCode-Sort Colors II
- leetcode每日一題LeetCode每日一題
- Leetcode每日一題:992.sort-array-by-parity-ii(按奇偶排序陣列Ⅱ)LeetCode每日一題排序陣列
- Leetcode每日一題(1)LeetCode每日一題
- LeetCode 每日一題「判定字元是否唯一」LeetCode每日一題字元
- LeetCode每日一題:Nim遊戲(No.292)LeetCode每日一題遊戲
- LeetCode每日一題: 找不同(No.389)LeetCode每日一題
- LeetCode每日一題: 移除元素(No.27)LeetCode每日一題
- LeetCode每日一題: 移動零(No.283)LeetCode每日一題
- LeetCode每日一題:自除數(No.728)LeetCode每日一題
- LeetCode每日一題:迴文數(No.9)LeetCode每日一題
- LeetCode每日一題:兩數之和(No.1)LeetCode每日一題
- LeetCode每日一題:爬樓梯(No.70)LeetCode每日一題
- LeetCode每日一題: 排列硬幣(No.441)LeetCode每日一題
- LeetCode每日一題: 各位相加(No.258)LeetCode每日一題
- LeetCode每日一題:longest palindromic substringLeetCode每日一題
- LeetCode 2024/6 每日一題 合集LeetCode每日一題
- Leetcode每日一題:面試題16.19.水域大小LeetCode每日一題面試題
- LeetCode每日一題:整數反轉(No.7)LeetCode每日一題
- LeetCode每日一題:求眾數(No.169)LeetCode每日一題
- LeetCode每日一題: 轉置矩陣(No.867)LeetCode每日一題矩陣
- LeetCode每日一題:最長公共字首(No.14)LeetCode每日一題
- LeetCode每日一題: 搜尋插入位置(No.35)LeetCode每日一題
- 【js】Leetcode每日一題-葉子相似的樹JSLeetCode每日一題
- 【LeetCode】每日一題164. 最大間距LeetCode每日一題
- LeetCode:每日一題:27. 移除元素 ——————簡單LeetCode每日一題
- 【leetcode】(每日一題 771 寶石與石頭)LeetCode每日一題
- LeetCode每日一題 (32)1. 兩數之和LeetCode每日一題
- Leetcode Sort ArrayLeetCode
- LeetCode每日一題: 旋轉陣列(No.189)LeetCode每日一題陣列
- LeetCode每日一題: 按奇偶排序陣列(No.905)LeetCode每日一題排序陣列
- LeetCode每日一題: 檸檬水找零(No.860)LeetCode每日一題