From 79274e5a3357232adb9b4d010f6c3b24a42153dc Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 1 Sep 2022 13:34:17 +0800 Subject: [PATCH] vault backup: 2022-09-01 13:34:17 --- .obsidian/appearance.json | 2 +- Leetcode Sort-Colors.md | 75 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 Leetcode Sort-Colors.md diff --git a/.obsidian/appearance.json b/.obsidian/appearance.json index d87f1f1..7324f87 100644 --- a/.obsidian/appearance.json +++ b/.obsidian/appearance.json @@ -1,5 +1,5 @@ { - "theme": "obsidian", + "theme": "moonstone", "translucency": true, "cssTheme": "Atom", "interfaceFontFamily": "IBM Plex Sans", diff --git a/Leetcode Sort-Colors.md b/Leetcode Sort-Colors.md new file mode 100644 index 0000000..f801b68 --- /dev/null +++ b/Leetcode Sort-Colors.md @@ -0,0 +1,75 @@ +# Leetcode Sort-Colors + +#### 2022-09-01 13:24 + +> ##### Algorithms: +> #algorithm #two_pointers +> ##### Data structures: +> #DS #array +> ##### Difficulty: +> #coding_problem #difficulty-medium +> ##### Additional tags: +> #leetcode +> ##### Revisions: +> N/A + +##### Links: +- [Link to problem](https://leetcode.com/problems/sort-colors/) +___ +### Problem + +Given an array `nums` with `n` objects colored red, white, or blue, sort them **[in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** 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. + +#### Examples + +**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] + +#### Constraints + +- `n == nums.length` +- `1 <= n <= 300` +- `nums[i]` is either `0`, `1`, or `2`. + +### Thoughts + +> [!summary] +> This is a variant of double pointer method. + +Simple double pointer method, check for cur and pointers to +avoid infinite loops. + +### Solution + +```cpp +class Solution { +public: + void sortColors(vector &nums) { + // Double pointer + int lowptr = 0; + int highptr = nums.size() - 1; + int cur = 0; + + for (int size = nums.size(); cur < size; cur++) { + if (nums[cur] == 0 && cur != lowptr) { + swap(nums[lowptr++], nums[cur]); + cur--; + } else if (nums[cur] == 2 && cur < highptr) { + swap(nums[highptr--], nums[cur]); + cur--; + } + } + } +}; +``` \ No newline at end of file