Local Minimum in a array using lg N

Algorithms fourth edition at http://algs4.cs.princeton.edu/14analysis/

Chapter 1. 1.4 Analysis of Algorithms

Creative Problems 18

  1. Local minimum of an array. Write a program that, given an array a[] of N distinct integers, finds a local minimum: an index i such that botha[i] < a[i-1] and a[i] < a[i+1] (assuming the neighboring entry is in bounds). Your program should use ~2 lg N compares in the worst case.

    Answer: Examine the middle value a[N/2] and its two neighbors a[N/2 - 1] and a[N/2 + 1]. If a[N/2] is a local minimum, stop; otherwise search in the half with the smaller neighbor.

实现类似的算法在http://blog.csdn.net/sunmenggmail/article/details/8233164中提到,只不过没有给出解释.
这里面提到的实现方法中边界条件不完善
if(a[nBeg]>a[nEnd]) return a[eEnd];
else return a[eBeg];

Explanation:

三种情况:

Case 1:当a[N/2 - 1] < a[N/2],假设满足0<i<N/2的a[i]中不存在local minimum, 则a[N/2 - 2] < a[N/2 - 1].依次类推最后得a[0]<a[1].但此时a[0]为local minimum。

所以0<i<N/2时必然存在local minimum。

Case 2:当a[N/2 + 1] <a[N/2]时,与Case 1类似。

Case 3:当a[N/2 - 1] > a[N/2]且a[N/2 + 1] > a[N/2]时a[N/2]为local minimum


Notes:

从NxN的2维数组寻找local minimum的时候也可以采取类似的方法。满足O(n)

http://stackoverflow.com/questions/18525179/find-local-minimum-in-n-x-n-matrix-in-on-time

从N/2列和N/2行选择最小的元素,依次类推到找到local minimum为止

local minimum的范围不会超过N/2xN/2,因为N/2xN/2内的值比N/2行与N/2列的最小值还小

所以worst case下找到local minimum需要 2N + 2N/2 + 2N/4 + ... = 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值