Skip to content

2024-07-23 v. 6.2.7: added "75. Sort Colors" #686

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
2 changes: 1 addition & 1 deletion leetcode-ruby.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
35 changes: 35 additions & 0 deletions lib/medium/75_sort_colors.rb
Original file line number Diff line number Diff line change
@@ -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
17 changes: 17 additions & 0 deletions test/medium/test_75_sort_colors.rb
Original file line number Diff line number Diff line change
@@ -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
Loading