mirror of
https://github.com/krahets/hello-algo.git
synced 2026-02-04 03:14:09 +08:00
* Review the EN heading format. * Fix pythontutor headings. * Fix pythontutor headings. * bug fixes * Fix headings in **/summary.md * Revisit the CN-to-EN translation for Python code using Claude-4.5 * Revisit the CN-to-EN translation for Java code using Claude-4.5 * Revisit the CN-to-EN translation for Cpp code using Claude-4.5. * Fix the dictionary. * Fix cpp code translation for the multipart strings. * Translate Go code to English. * Update workflows to test EN code. * Add EN translation for C. * Add EN translation for CSharp. * Add EN translation for Swift. * Trigger the CI check. * Revert. * Update en/hash_map.md * Add the EN version of Dart code. * Add the EN version of Kotlin code. * Add missing code files. * Add the EN version of JavaScript code. * Add the EN version of TypeScript code. * Fix the workflows. * Add the EN version of Ruby code. * Add the EN version of Rust code. * Update the CI check for the English version code. * Update Python CI check. * Fix cmakelists for en/C code. * Fix Ruby comments
47 lines
998 B
Ruby
47 lines
998 B
Ruby
=begin
|
|
File: two_sum.rb
|
|
Created Time: 2024-04-09
|
|
Author: Blue Bean (lonnnnnnner@gmail.com)
|
|
=end
|
|
|
|
### Method 1: Brute force enumeration ###
|
|
def two_sum_brute_force(nums, target)
|
|
# Two nested loops, time complexity is O(n^2)
|
|
for i in 0...(nums.length - 1)
|
|
for j in (i + 1)...nums.length
|
|
return [i, j] if nums[i] + nums[j] == target
|
|
end
|
|
end
|
|
|
|
[]
|
|
end
|
|
|
|
### Method 2: Auxiliary hash table ###
|
|
def two_sum_hash_table(nums, target)
|
|
# Auxiliary hash table, space complexity is O(n)
|
|
dic = {}
|
|
# Single loop, time complexity is O(n)
|
|
for i in 0...nums.length
|
|
return [dic[target - nums[i]], i] if dic.has_key?(target - nums[i])
|
|
|
|
dic[nums[i]] = i
|
|
end
|
|
|
|
[]
|
|
end
|
|
|
|
### Driver Code ###
|
|
if __FILE__ == $0
|
|
# ======= Test Case =======
|
|
nums = [2, 7, 11, 15]
|
|
target = 13
|
|
|
|
# ====== Driver Code ======
|
|
# Method 1
|
|
res = two_sum_brute_force(nums, target)
|
|
puts "Method 1 res = #{res}"
|
|
# Method 2
|
|
res = two_sum_hash_table(nums, target)
|
|
puts "Method 2 res = #{res}"
|
|
end
|