diff --git a/README.md b/README.md index f44fc0a7..c279aa59 100644 --- a/README.md +++ b/README.md @@ -492,3 +492,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/). | 62. Unique Paths | [Link](https://leetcode.com/problems/unique-paths/) | [Link](./lib/medium/62_unique_paths.rb) | | 71. Simplify Path | [Link](https://leetcode.com/problems/simplify-path/) | [Link](./lib/medium/71_simplify_path.rb) | | 74. Search a 2D Matrix | [Link](https://leetcode.com/problems/search-a-2d-matrix/) | [Link](./lib/medium/74_search_a_2d_matrix.rb) | +| 75. Sort Colors | [Link](https://leetcode.com/problems/sort-colors/) | [Link](./lib/medium/75_sort_colors.rb) | diff --git a/leetcode-ruby.gemspec b/leetcode-ruby.gemspec index 06bf0b07..4c86195e 100644 --- a/leetcode-ruby.gemspec +++ b/leetcode-ruby.gemspec @@ -5,7 +5,7 @@ require 'English' ::Gem::Specification.new do |s| s.required_ruby_version = '>= 3.0' s.name = 'leetcode-ruby' - s.version = '6.2.6' + s.version = '6.2.7' s.license = 'MIT' s.files = ::Dir['lib/**/*.rb'] + %w[README.md] s.executable = 'leetcode-ruby' diff --git a/lib/medium/75_sort_colors.rb b/lib/medium/75_sort_colors.rb new file mode 100644 index 00000000..11337b8f --- /dev/null +++ b/lib/medium/75_sort_colors.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +# https://leetcode.com/problems/sort-colors/ +# @param {Integer[]} nums +# @return {Void} Do not return anything, modify nums in-place instead. +def sort_colors(nums) + l = 0 + m = 0 + h = nums.length - 1 + + while m <= h + if nums[m].zero? + swap(nums, m, l) + m += 1 + l += 1 + elsif nums[m] == 1 + m += 1 + else + swap(nums, m, h) + h -= 1 + end + end +end + +private + +# @param {Integer[]} nums +# @param {Integer} f +# @param {Integer} s +# @return {Void} +def swap(nums, f, s) + temp = nums[f] + nums[f] = nums[s] + nums[s] = temp +end diff --git a/test/medium/test_75_sort_colors.rb b/test/medium/test_75_sort_colors.rb new file mode 100644 index 00000000..c35df06c --- /dev/null +++ b/test/medium/test_75_sort_colors.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +require_relative '../test_helper' +require_relative '../../lib/medium/75_sort_colors' +require 'minitest/autorun' + +class SortColorsTest < ::Minitest::Test + def test_default + nums = [2, 0, 2, 1, 1, 0] + sort_colors(nums) + assert_equal([0, 0, 1, 1, 2, 2], nums) + + nums = [2, 0, 1] + sort_colors(nums) + assert_equal([0, 1, 2], nums) + end +end