mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
data-structure(i): add day 1
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
275d28ec33
commit
9fa39e8873
3 changed files with 56 additions and 0 deletions
27
study-plan/data-structure/day-1/contains-duplicate.rb
Normal file
27
study-plan/data-structure/day-1/contains-duplicate.rb
Normal file
|
@ -0,0 +1,27 @@
|
|||
# @param {Integer[]} nums
|
||||
# @return {Boolean}
|
||||
def contains_duplicate(nums)
|
||||
encountered = Set.new
|
||||
|
||||
nums.each { |x|
|
||||
if encountered.add?(x) == nil then
|
||||
return true
|
||||
end
|
||||
}
|
||||
|
||||
return false
|
||||
end
|
||||
|
||||
RSpec.describe "contains_duplicate" do
|
||||
it "nums = [1,2,3,1] contains" do
|
||||
expect(contains_duplicate([1,2,3,1])).to be true
|
||||
end
|
||||
|
||||
it "nums = [1,2,3,4] doesn't contain" do
|
||||
expect(contains_duplicate([1,2,3,4])).to be false
|
||||
end
|
||||
|
||||
it "nums = [1,1,1,3,3,4,3,2,4,2] contains" do
|
||||
expect(contains_duplicate([1,1,1,3,3,4,3,2,4,2])).to be true
|
||||
end
|
||||
end
|
29
study-plan/data-structure/day-1/maximum-subarray.rb
Normal file
29
study-plan/data-structure/day-1/maximum-subarray.rb
Normal file
|
@ -0,0 +1,29 @@
|
|||
# @param {Integer[]} nums
|
||||
# @return {Integer}
|
||||
def max_sub_array(nums)
|
||||
if nums.empty? then
|
||||
return nil
|
||||
end
|
||||
|
||||
sum, running_sum = nums.first, nums.first
|
||||
nums.drop(1).each { |x|
|
||||
running_sum = [running_sum + x, x].max
|
||||
sum = [sum, running_sum].max
|
||||
}
|
||||
|
||||
return sum
|
||||
end
|
||||
|
||||
RSpec.describe "max_sub_array of " do
|
||||
it "[-2,1,-3,4,-1,2,1,-5,4] is 6" do
|
||||
expect(max_sub_array([-2,1,-3,4,-1,2,1,-5,4])).to eq(6)
|
||||
end
|
||||
|
||||
it "[1] is 1" do
|
||||
expect(max_sub_array([1])).to eq(1)
|
||||
end
|
||||
|
||||
it "[5,4,-1,7,8] is 23" do
|
||||
expect(max_sub_array([5,4,-1,7,8])).to eq(23)
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue