Complexity with Array.min
I have an array:
[0, 0, 0, 0, 0, 0, 0, 1, 2, 3]
I need to figure out index of the minimal e开发者_Go百科lement which is not zero. How do I do that?
For ruby 1.8.7+:
>> [0,0,2,0,1,3].each_with_index.reject {|(e, i)| e == 0}
=> [[2, 2], [1, 4], [3, 5]]
>> [0,0,2,0,1,3].each_with_index.reject {|(e, i)| e == 0}.min
=> [1, 4]
>> [0,0,2,0,1,3].each_with_index.reject {|(e, i)| e == 0}.min[1]
=> 4
For ruby 1.8.6:
a.zip((0...a.size).to_a).reject {|(e, i)| e == 0}.min[1]
(solution by chuck)
a=[0, 0, 0, 0, 0, 0, 0, 1, 2, 3]
i=a.index a.reject{|x|x==0}.min
(i=7)
Simplest way: check each element of the array, keep a variable that is the minimum, set it equal to the first number you come across (unless 0, then discard and use next number). Any time you come across a number smaller than your minimum, set it to your minimum. And, of course, discard any zero rather than setting your minimum.
More efficient: It appears we have a sorted array, if we can use that to our advantage, we can use a better search mechanism, such as quick-search or binary-search. I will describe binary search as it is easy to understand.
Our array is in ascending order. Check the middle most element, set it equal to your minimum (unless 0). Split the array in half on this middle element. Since the array is ascending, check the middle point of the left half (unless element was 0, then check right). Continue until there is only one element to the left when you split. That is your minimum.
I don't know Ruby, so I can't offer code, but the process that immediately springs to my mind is:
- Create a copy of the array (if needed)
- Remove all the
0
entries - Check the minimum value in the new array
精彩评论