LeetCode 702. Search in a Sorted Array of Unknown Size
Posted brooksli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 702. Search in a Sorted Array of Unknown Size相关的知识,希望对你有一定的参考价值。
仍然是二分法专栏系列
现在的问题是在不知道sorted array大小的情况下得知是否含有target元素
接口是 ArrayReader: reader.get(index)
如果超出界限 则返回 Integer.MAX_VALUE;
思路:1.首先找到比target大的右边界限 或者是已经越界的界限
2.在left , right 界限中间使用二分法进行查找
public int search(ArrayReader reader, int target) { //Corner case if(reader==null){ return -1; } int left=0; int right=1; while(reader.get(right)!=Integer.MAX_VALUE && reader.get(right)<target){ left=right; right=right*2; } return binarySearch(reader,target,left,right); } private int binarySearch(ArrayReader reader,int target,int left,int right){ while(left<=right){ int mid=left+(right-left)/2; if(reader.get(mid)==Integer.MAX_VALUE || reader.get(mid)>target){ right=mid-1; }else if(reader.get(mid)<target){ left=mid+1; }else{ return mid; } } return -1; }
以上是关于LeetCode 702. Search in a Sorted Array of Unknown Size的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 702. Search in a Sorted Array of Unknown Size
[LeetCode&Python] Problem 700. Search in a Binary Search Tree
Leetcode Search in Rotated Sorted Array
[Leetcode]700. Search in a Binary Search Tree
LeetCode | 0700. Search in a Binary Search Tree二叉搜索树中的搜索Python