# 新手问题 [Ruby] leetcode everyday

bluefish733 · 2019年05月09日 · 最后由 bluefish733 回复于 2019年05月13日 · 1367 次阅读

``````# 4. Median of Two Sorted Arrays
# There are two sorted arrays nums1 and nums2 of size m and n respectively.
# Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
# You may assume nums1 and nums2 cannot be both empty.
# Example 1:
# nums1 = [1, 3]
# nums2 = [2]
# The median is 2.0
# Example 2:
# nums1 = [1, 2]
# nums2 = [3, 4]
# The median is (2 + 3)/2 = 2.5
# @param {Integer[]} nums1
# @param {Integer[]} nums2
# @return {Float}
def find_median_sorted_arrays(nums1, nums2)
return 0 if nums1.empty? && nums2.empty?
if nums1.empty?||nums2.empty?
len = nums1.size | nums2.size
if len % 2 == 1
return nums1.empty? ? nums2[len/2] : nums1[len/2]
elsif len % 2 == 0
return nums1.empty? ? (nums2[len/2 - 1] + nums2[len/2]).to_f/2 : (nums1[len/2 - 1] + nums1[len/2]).to_f/2
end
end
nums2.each do |i|
nums1[nums1.size,0]=i
# print nums1
end
nums11 = nums1.sort
l = nums11.size
return l % 2 == 0 ? (nums11[l / 2] + nums11[l / 2 - 1]).to_f / 2 : nums11[l / 2].to_f
end
``````
``````# 6. ZigZag Conversion

# Input: s = "PAYPALISHIRING", numRows = 4
# Output: "PINALSIGYAHRPI"
# Explanation:

# P     I    N
# A   L S  I G
# Y A   H R
# P     I

# @param {String} s
# @param {Integer} num_rows
# @return {String}
def convert(s, num_rows)
len = s.size
res = ""
# 特殊情况，如　"" , 2
return res if len == 0
# 特殊情况，如　"A",2 或者 "ABC" , 1
return s if num_rows >= len || num_rows == 1
addition = 2 * num_rows - 2
# repeat为能"写"出的Ｚ字型的个数
repeat = (len - num_rows) / addition + 1
num_rows.times do |i|
# 每次循环s[i]分别为
# Ｐ
# Ａ
# Ｙ
# Ｐ
res = res + s[i]
# i表示第几行，ｊ表示第几个Ｚ字型
repeat.times do |j|
if i==0 || i==num_rows - 1
else
end
end
end
return res
end

# 看到一个好理解又简洁的版本，马来学习
# position表示第几行，direction表示上一行还是下一行，在两个判断条件处决定
# 这个代码是按字符串中字符顺序分别存到buf的第几个单元中，每个单元表示一行，最后join一下
# 相比之下，我的代码是直接将结果存在res中，然后输出res
def convert(s, num_rows)
return s if num_rows ==1
buf = num_rows.times.collect{[]}
position = 0
direction=1
s.each_char do |c|
buf[position]<< c
if position+direction==num_rows
direction=-1
elsif position+direction==-1
direction=1
end
position+=direction
end
buf.join
end
``````
``````# 8. String to Integer (atoi)
# 发现可以直接用to_i，，， 简直了
# @param {String} str
# @return {Integer}
def my_atoi(str)
# return 0 if str.empty? || str[0] != '-' || str[0] != '+' || !((48..57) === str[0].ord)
res = /[-|+]?[0-9]*/.match(str.lstrip).to_s.to_i
res = res > (2**31 - 1) ? (2**31 - 1) : (res <(-2**31) ? (-2**31) : res)
return res
end
``````

To be continued…

awking 回复

hiveer 回复