码迷,mamicode.com
首页 > 其他好文 > 详细

Searching in a rotated and sorted array

时间:2014-07-11 23:02:53      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:des   blog   http   width   2014   io   

Given a sorted array that has been rotated serveral times. Write code to find an element in this array. You may assume that the array was originally sorted in increasing order.

思路:first to know that to ratate an array multiple times is no different than to rotate it just once.

No matter how the array has been rotated, it would fall into 3 kinds of situations below:

bubuko.com,布布扣

#1: If array[low] < array[mid], then left side is ordered normally.

#2: If array[mid] < array[high], then right side is ordered normally.

#3: array[mid] = array[low] = array[high], this might occur only when duplicates are allowed. In this condition, we have to search both sides because we don‘t know which side is ordered normally.

 

Note: a little tricky thing is that when array has exactly 2 elements, the above logic may go wrong, so just consider this situation separately.

Searching in a rotated and sorted array,布布扣,bubuko.com

Searching in a rotated and sorted array

标签:des   blog   http   width   2014   io   

原文地址:http://www.cnblogs.com/Antech/p/3832935.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!