我一直在Ruby中練習一些練習題,經常出現這個問題。爲什麼我應該在聲明一個變量時指定nil而不是給它一個基值?
比方說,我試圖在整型數組
def third_greatest(nums)
first = 0
second = 0
third = 0
i = 0
while(i < nums.length)
if nums[i] > first
third = second
second = first
first= nums[i]
elsif nums[i] > second
third = second
second = nums[i]
elsif nums[i] > third
third = nums[i]
end
i+=1
end
return third
end
此代碼確實滿足了測試用例提供
但是給出的解決辦法初始化與零變量求解第三大整數並在每個if語句中進行額外檢查,如果變量爲零
def third_greatest(nums)
first = nil
second = nil
third = nil
idx = 0
while idx < nums.length
value = nums[idx]
if first == nil || value > first
third = second
second = first
first = value
elsif second == nil || value > second
third = second
second = value
elsif third == nil || value > third
third = value
end
idx += 1
end
return third
end
在哪些情況下我的代碼不正確?哪個代碼更好?在案例2中感覺更加麻煩,儘管我可以想象有些情況下我的解決方案可能無法工作。
如果什麼號數組包含一個0?這應該算什麼? – Yule