33 Search in Rotated Sorted Array

原创 2016年05月31日 22:13:47


直接二分,例如原数组{0,1,2,4,5,6,7}   旋转为 {7,0,1,2,4,5,6}


找到数组中间位置,分成左右两半 {7,0,1,2} 和 {4,5,6}


比较数组的两端的元素大小,利用原数组是有序的这个重要性质: 如果满足ele[lo]<=ele[hi],此时表明不含旋转点,可直接二分查找。


若不满足ele[lo]<=ele[hi],表明包含旋转点,继续二分数组


public int search(int[] nums, int target)
	{
		return searchaux(nums, target, 0,nums.length-1);
	}
	
	public int searchaux(int[] nums,int target,int lo,int hi)
	{
		int ret=-1;
		if(nums[lo]<=nums[hi])
			ret=Arrays.binarySearch(nums, lo, hi+1, target);
		else {
			int mid=(lo+hi)>>1;
			int a=searchaux(nums, target, lo, mid);
			int b=searchaux(nums, target, mid+1, hi);
			ret=Math.max(a, b);
			
		}
		
		if(ret<0)
			ret=-1;
		return ret;
	}


版权声明:本文为博主原创文章,未经博主允许【可以】转载

相关文章推荐

leetcode解题之33&81. Search in Rotated Sorted Array java版(在旋转的数字中查找指定值)

33. Search in Rotated Sorted Array ,81. Search in Rotated Sorted Array II 。 leetcode解题之33&81. Search...

leetcode(33). Search in Rotated Sorted Array

problem Suppose an array sorted in ascending order is rotated at some pivot unknown to you befo...

LeetCode OJ 33 Search in Rotated Sorted Array

难度:hard 由此可见leetcode的hard难度比较于acm是偏简单一些的。 Suppose a sorted array is rotated at some pivot unkn...
  • LLL_mj
  • LLL_mj
  • 2015年07月06日 18:21
  • 296

[leetcode] 33. 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 mig...

Leetcode 33 - Search in Rotated Sorted Array(二分)

题意给一个有序数组,然后从数组的某一个位置,将前后两半交换。现在给一个数k,求k在数组中出现的位置,如果没有出现,返回-1。思路算法1画个图,其实就两种情况:前半段长还是后半段长,然后分若干种情况去讨...
  • Lzedo
  • Lzedo
  • 2017年02月13日 16:44
  • 88

33/81. Search in Rotated Sorted Array I/II(C++)

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.(i.e.,...

【C++】【LeetCode】33. Search in Rotated Sorted Array

题目Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i...
  • zjajgyy
  • zjajgyy
  • 2017年06月11日 15:51
  • 75

LeetCode33——Search in Rotated Sorted Array

LeetCode33——Search in Rotated Sorted Array 简单来说就是在数组中查找  输入的  target,如果找到返回索引,如果没有找到返回-1 在中S...

LeetCode: 33. Search in Rotated Sorted Array

LeetCode: 33. Search in Rotated Sorted Array

[Leetcode]33(81). Search in Rotated Sorted Array I, II

题目大意: Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:33 Search in Rotated Sorted Array
举报原因:
原因补充:

(最多只允许输入30个字)