Question Description
Idea
输入一个数组,将其转化为行列 r, c的新矩阵。如果不能转化,则返回旧矩阵。
这里当新矩阵的r*c不等于原矩阵的size就认为不能转化了,很坑。
本题的测试用例设计的很不用心啊...本身的代码写出了判断最后要求输出的是一维数组还是二维数组的功能,但是实际上本题的输出全是二维数组,也就是说要写成[ [1,2,3,4] ]
一般来说有三种思路,前两种基本相同,最后的Big O也都相同
第一种就是按顺序把原数组的内容全缓存到一个vector里,用ruby的话其实就Array.flatten!
一下就好了
第二种就是直接遍历原数组,不用中间存储
第三种呢是不判断是否到了行尾,用[count/c][count%c]
来计算index
Solution
Solution 2a
def matrix_reshape(nums, r, c)
# determine whether the array is 2-dimension or not
is_2d = nums[0].kind_of?(Array)
size = is_2d ? nums.size * nums[0].size : nums.size
return nums if r*c != size
cur_row, cur_col = 0, 0
resharp_nums = []
resharp_nums[cur_row] = []
# handle the situation that the array is 1D array
nums.flatten!
nums.each do |num|
next if num.nil?
if cur_col == c then
cur_col = 0
cur_row += 1
resharp_nums[cur_row] = []
end
resharp_nums[cur_row] << num
cur_col += 1
end
return resharp_nums
end
Solution 2b
# @param {Integer[][]} nums
# @param {Integer} r
# @param {Integer} c
# @return {Integer[][]}
def matrix_reshape(nums, r, c)
# determine whether the array is 2-dimension or not
is_2d = nums[0].kind_of?(Array)
size = is_2d ? nums.size * nums[0].size : nums.size
return nums if r*c != size
cur_row, cur_col = 0, 0
resharp_nums = []
resharp_nums[cur_row] = []
# handle the situation that the array is 1D array
if is_2d then
nums.each do |row|
row.each do |num|
next if num.nil?
if cur_col == c then
cur_col = 0
cur_row += 1
resharp_nums[cur_row] = []
end
resharp_nums[cur_row] << num
cur_col += 1
end
end
else
nums.each do |num|
next if num.nil?
if cur_col == c then
cur_col = 0
cur_row += 1
resharp_nums[cur_row] = []
end
resharp_nums[cur_row] << num
cur_col += 1
end
end
return resharp_nums
end
Solution 3
其实还是遍历双层for循环,没啥卵用,先不写了,等下次写到新建二维数组的时候再补上