[LintCode] 447 Search in a Big Sorted Array

本文介绍了一种在未知长度的大排序数组中寻找目标数首个出现位置的算法。该算法通过逐步扩大搜索范围,再进行二分查找的方式,在O(log k)的时间复杂度内找到目标数的首个索引。

Description
Given a big sorted array with positive integers sorted by ascending order. The array is so big so that you can not get the length of the whole array directly, and you can only access the kth number by ArrayReader.get(k) (or ArrayReader->get(k) for C++). Find the first index of a target number. Your algorithm should be in O(log k), where k is the first index of the target number.

Return -1, if the number doesn't exist in the array.

Notice
If you accessed an inaccessible index (outside of the array), ArrayReader.get will return 2,147,483,647.

4/23/2017

算法班

注意题目要求是返回第一个index

 1     public int searchBigSortedArray(ArrayReader reader, int target) {
 2         // ArrayReader.get(k);
 3         int startIndex = 0;
 4         while (reader.get(startIndex) < target) {
 5             startIndex *= 2;
 6         }
 7         int start = startIndex / 2, end = startIndex;
 8 
 9         while (start + 1 < end) {
10             int mid = start + (end - start) / 2;
11             if (reader.get(mid) >= target) {
12                 end = mid;
13             } else {
14                 start = mid;
15             }
16         }
17         if (reader.get(start) == target) return start;
18         if (reader.get(end) == target) return end;
19         return -1;
20     }

 

转载于:https://www.cnblogs.com/panini/p/6755128.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值