2015-07-03 29 views
0

我一直在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

如果什麼號數組包含一個0?這應該算什麼? – Yule

回答

1

您的代碼不適用於負數。和:

$> nil > -1 
NoMethodError: undefined method `>' for nil:NilClass 

這對在第二種情況下零檢查的原因

1

你的代碼不正確時,第三大整數小於0時,或者當陣列少於三人。

第二個代碼更好,但它仍然不好。使第二個代碼更Rubyish可以是這樣的:

def third_greatest(nums) 
    a = [] 
    nums.each do |i| 
    if !a[0] || i > a[0] then a.insert(0, i) 
    elsif !a[1] || i > a[1] then a.insert(1, i) 
    elsif !a[2] || i > a[2] then a.insert(2, i) 
    end 
    end 
    a[2] 
end 
0

說數量是[0,-5,8,-15]。零將被忽略,所以你應該擁有第三大-15,而不是-5。

一般來說,nil最好是分配一個可以由您的代碼分配的任意值,邏輯/流可能會中斷。

IMO上述兩個版本的代碼都很糟糕。

只是nums.sort.reverse[2]應該得到你的價值,或者如果你想第三大獨特的價值:nums.uniq.sort.reverse[2]

相關問題