一道面試題-一任意整數數組。寫一個函數,把數組裏的奇數放前面。偶數放後面。...

一坨任意整數數組。寫一個函數,把數組裏的奇數放前面。偶數放後面。來自[url]http://blog.csdn.net/g9yuayon/article/details/2679202[/url]
想到了算法之一
# this function is used to move all odd number to front part of an array and even numbers end.
def test(arr)
endix = arr.size-1
arr.each_with_index do |v,i|
if i >= endix
return
end

if v % 2 == 0 # met a even
# swap this even with the last odd
until arr[endix] % 2 == 1 or endix <= i
endix -= 1
end
arr[i],arr[endix]=arr[endix],arr[i]
end
end
end

時間複雜度是O(n),空間複雜度是O(1).
發佈了48 篇原創文章 · 獲贊 1 · 訪問量 3311
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章