Question Description
Idea
輸入一個數(shù)組迂尝,將其轉(zhuǎn)化為行列 r, c的新矩陣。如果不能轉(zhuǎn)化疏咐,則返回舊矩陣扬舒。
這里當(dāng)新矩陣的r*c不等于原矩陣的size就認(rèn)為不能轉(zhuǎn)化了阐肤,很坑。
本題的測試用例設(shè)計的很不用心啊...本身的代碼寫出了判斷最后要求輸出的是一維數(shù)組還是二維數(shù)組的功能讲坎,但是實際上本題的輸出全是二維數(shù)組孕惜,也就是說要寫成[ [1,2,3,4] ]
一般來說有三種思路,前兩種基本相同晨炕,最后的Big O也都相同
第一種就是按順序把原數(shù)組的內(nèi)容全緩存到一個vector里衫画,用ruby的話其實就Array.flatten!
一下就好了
第二種就是直接遍歷原數(shù)組,不用中間存儲
第三種呢是不判斷是否到了行尾瓮栗,用[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循環(huán)削罩,沒啥卵用,先不寫了遵馆,等下次寫到新建二維數(shù)組的時候再補(bǔ)上