一坨任意整数数组。写一个函数,把数组里的奇数放前面。偶数放后面。来自[url]http://blog.youkuaiyun.com/g9yuayon/article/details/2679202[/url]
想到了算法之一
时间复杂度是O(n),空间复杂度是O(1).
想到了算法之一
# 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).
将数组中奇数移至前部的高效算法
本文介绍了一个将任意整数数组中奇数元素移动至前部,偶数元素移至后部的算法。该算法的时间复杂度为O(n),空间复杂度为O(1),详细步骤包括遍历数组并使用交换操作实现元素重新排列。
596

被折叠的 条评论
为什么被折叠?



