Skip to content

Commit e7e5a57

Browse files
committed
2024-07-23 v. 6.2.7: added "75. Sort Colors"
1 parent 0332496 commit e7e5a57

File tree

4 files changed

+54
-1
lines changed

4 files changed

+54
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,3 +492,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
492492
| 62. Unique Paths | [Link](https://leetcode.com/problems/unique-paths/) | [Link](./lib/medium/62_unique_paths.rb) |
493493
| 71. Simplify Path | [Link](https://leetcode.com/problems/simplify-path/) | [Link](./lib/medium/71_simplify_path.rb) |
494494
| 74. Search a 2D Matrix | [Link](https://leetcode.com/problems/search-a-2d-matrix/) | [Link](./lib/medium/74_search_a_2d_matrix.rb) |
495+
| 75. Sort Colors | [Link](https://leetcode.com/problems/sort-colors/) | [Link](./lib/medium/75_sort_colors.rb) |

leetcode-ruby.gemspec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ require 'English'
55
::Gem::Specification.new do |s|
66
s.required_ruby_version = '>= 3.0'
77
s.name = 'leetcode-ruby'
8-
s.version = '6.2.6'
8+
s.version = '6.2.7'
99
s.license = 'MIT'
1010
s.files = ::Dir['lib/**/*.rb'] + %w[README.md]
1111
s.executable = 'leetcode-ruby'

lib/medium/75_sort_colors.rb

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# frozen_string_literal: true
2+
3+
# https://leetcode.com/problems/sort-colors/
4+
# @param {Integer[]} nums
5+
# @return {Void} Do not return anything, modify nums in-place instead.
6+
def sort_colors(nums)
7+
l = 0
8+
m = 0
9+
h = nums.length - 1
10+
11+
while m <= h
12+
if nums[m].zero?
13+
swap(nums, m, l)
14+
m += 1
15+
l += 1
16+
elsif nums[m] == 1
17+
m += 1
18+
else
19+
swap(nums, m, h)
20+
h -= 1
21+
end
22+
end
23+
end
24+
25+
private
26+
27+
# @param {Integer[]} nums
28+
# @param {Integer} f
29+
# @param {Integer} s
30+
# @return {Void}
31+
def swap(nums, f, s)
32+
temp = nums[f]
33+
nums[f] = nums[s]
34+
nums[s] = temp
35+
end

test/medium/test_75_sort_colors.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# frozen_string_literal: true
2+
3+
require_relative '../test_helper'
4+
require_relative '../../lib/medium/75_sort_colors'
5+
require 'minitest/autorun'
6+
7+
class SortColorsTest < ::Minitest::Test
8+
def test_default
9+
nums = [2, 0, 2, 1, 1, 0]
10+
sort_colors(nums)
11+
assert_equal([0, 0, 1, 1, 2, 2], nums)
12+
13+
nums = [2, 0, 1]
14+
sort_colors(nums)
15+
assert_equal([0, 1, 2], nums)
16+
end
17+
end

0 commit comments

Comments
 (0)