假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
你可以假设数组中不存在重复元素。(此处代码有重复元素时同样适用)
示例 1:
输入: [3,4,5,1,2]
输出: 1
示例 2:
输入: [4,5,6,7,0,1,2]
输出: 0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array
有重复元素时原题链接:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/
代码:
local function findMinNum(a)
-- body
local a = a
local left = 1
local right = #a
local cut = math.modf((right+left)/2)
while not (a[cut] > a[cut+1] and a[cut] < a[cut-1]) do
if left == right - 1 then return math.min(a[left],a[right]) end
if a[cut] < a[left] then
right = cut
else
left = cut
end
-- 二分
cut = math.modf((right+left)/2)
end
return a[cut]
end
local a = {4,5,6,7,8,9,11,0,1,2}
print(findMinNum(a))
结果:
0