`
huntfor
  • 浏览: 201229 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Search in Rotated Sorted Array

 
阅读更多

新博文地址:[leetcode]Search in Rotated Sorted Array

 

Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

 从一个转置排序数组中查找某个数,并返回下标,不存在则返回-1;

这道题要充分利用排序这个条件,因此可以使用折半查找,难点就在这个数组是由两个顺序数组拼接成的。

代码如下:

public int search(int[] a, int target) {
		int begin = 0;
		int end = a.length - 1;
		while (begin <= end) {
			int mid = (begin + end) >> 1;
			// make sure where middle element locates
			if (a[mid] == target) {
				return mid;
			} else if (target > a[mid]) {
				if (a[mid] > a[end]) {// 说明mid在前半段,那么target肯定在前半段
					begin = mid + 1;
				} else if (a[mid] < a[begin]) {// 说明mid在后半段,要么target在前半段,要么target在后半段
					if(target > a[end]){//target 在前半段
						end = mid - 1;
					}else if(target < a[begin]){//target在后半段
						begin = mid + 1;
					}
				} else {// 说明begin、end已经锁定到递增的序列里面了
					begin = mid + 1;
				}
			} else {//target比mid小
				if (a[mid] < a[begin]) {// 如果mid在后半段,说明target必须在后半段
					end = mid - 1;
				} else if (a[mid] > a[end]) {// mid在前半段
					if(target > a[end]){//target在前半段
						end = mid - 1;
					}else if(target < a[begin]){//target在后半段
						begin = mid + 1;
					}
				} else {// 说明begin、end已经锁定到递增的序列里面了
					end = mid - 1;
				}
			}
		}
		return -1;
	}

 将代码化简之后是这样的:

    public int search(int[] a, int target) {
		int begin = 0;
		int end = a.length - 1;
		while (begin <= end) {
			int mid = (begin + end) >> 1;
			if (a[mid] == target) {
				return mid;
			} else if (target > a[mid]) {
				if (a[mid] < a[begin] && target > a[end]) {
						end = mid - 1;
				} else {
					begin = mid + 1;
				}
			} else {
			    if (a[mid] > a[end] && target < a[begin]) {
						begin = mid + 1;
				} else {
					end = mid - 1;
				}
			}
		}
		return -1;
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics