Skip to content

Instantly share code, notes, and snippets.

@luchiago
Forked from marclerodrigues/balanced_string.rb
Created June 24, 2020 01:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luchiago/0e64dbc4a9bd546509ce124c65c27c42 to your computer and use it in GitHub Desktop.
Save luchiago/0e64dbc4a9bd546509ce124c65c27c42 to your computer and use it in GitHub Desktop.
Leet Code Problems
# @param {String} j
# @param {String} s
# @return {Integer}
def num_jewels_in_stones(j, s)
jewels = j.split("")
total = 0
s.split("").each do |stone|
total += 1 if jewels.include?(stone)
end
total
end
# @param {Integer[]} candies
# @param {Integer} extra_candies
# @return {Boolean[]}
def kids_with_candies(candies, extra)
max_candies = candies.max
candies.map do |candy|
candy + extra >= max_candies
end
end
def number_of_steps(num)
counter = 0
while num != 0
num = num.even? ? num / 2 : num - 1
counter += 1
end
counter
end
def number_of_steps(num)
steps = 0
while num != 0
num.even? ? num /= 2 : num -= 1
steps += 1
end
puts steps
end
def number_of_steps(num)
steps = 0
while num != 0
if num.even?
num = num/2
steps +=1
end
if num.odd?
num -= 1
steps +=1
end
end
steps
end
# @param {Integer} num
# @return {Integer}
def number_of_steps(num)
next_step(num, 0)
end
def next_step(value, step_count)
return step_count if value.zero?
if value.odd?
next_step(value - 1, step_count + 1)
else
next_step(value / 2, step_count + 1)
end
end
# @param {Integer[]} nums
# @return {Integer[]}
def running_sum(nums)
result = []
nums.each do |el|
previous_value = result.last || 0
result.push(previous_value + el)
end
result
end
# @param {Integer[]} nums
# @param {Integer} n
# @return {Integer[]}
def shuffle(nums, n)
(0..n). do |index|
first_half = nums[0...n]
second_half = nums[n..-1]
result = []
(0...n).each do |index|
result.push(first_half[index], second_half[index])
end
result
end
# @param {Integer[]} nums
# @param {Integer} n
# @return {Integer[]}
def shuffle(nums, n)
(0...n).flat_map do |index|
[nums[index], nums[index + n]]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment