mirror of
https://github.com/krahets/hello-algo.git
synced 2026-09-22 22:36:35 +08:00
build
This commit is contained in:
@@ -228,7 +228,17 @@ comments: true
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="two_sum.rb"
|
||||
[class]{}-[func]{two_sum_brute_force}
|
||||
### 方法一:暴力枚举 ###
|
||||
def two_sum_brute_force(nums, target)
|
||||
# 两层循环,时间复杂度为 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
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
@@ -531,7 +541,19 @@ comments: true
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="two_sum.rb"
|
||||
[class]{}-[func]{two_sum_hash_table}
|
||||
### 方法二:辅助哈希表 ###
|
||||
def two_sum_hash_table(nums, target)
|
||||
# 辅助哈希表,空间复杂度为 O(n)
|
||||
dic = {}
|
||||
# 单层循环,时间复杂度为 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
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
Reference in New Issue
Block a user