刚刚开始学 ruby,许多时候用什么方法还要先去查的情况~
各位走过路过、或者也在做题的童鞋欢迎前来指教,多谢多谢
# 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为上例中P和I,I和N在原字符串中位置的差
addition = 2 * num_rows - 2
# repeat为能"写"出的Z字型的个数
repeat = (len - num_rows) / addition + 1
num_rows.times do |i|
# 每次循环s[i]分别为
# P
# A
# Y
# P
res = res + s[i]
# i表示第几行,j表示第几个Z字型
repeat.times do |j|
if i==0 || i==num_rows - 1
res = res + s[addition*(j+1)+i] if addition*(j+1)+i < len
else
res = res + s[addition*(j+1)-i] if addition*(j+1)-i < len
res = res + s[addition*(j+1)+i] if addition*(j+1)+i < len
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…