本文主要是介绍leetcode解题方案--033--Search in Rotated Sorted Array,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
Suppose an array sorted in ascending order 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.
在一个旋转过的增序队列找某一个值。正常找值都会用二分法,这个其实也可以用;
但是要注意二分的下一区间不能简单的用mid值和target值判断了。
首先要判断当前区间是否为 含边界区间。含边界区间一定是num[right]
public static int search(int[] nums, int target) {if (nums == null ||nums.length<=0){return -1;}return find(nums,target,0,nums.length-1);}public static int find(int[] nums,int targer,int left,int right) {if (nums[left] == targer) {return left;}if (nums[right] ==targer){return right;}if ((right-left+nums.length)%nums.length<=1) {return -1;}//无边界增序int mid = left+(right-left)/2;if (nums[left] < nums[right]) {if (nums[mid]>targer) {return find(nums,targer,left,mid);} else {return find(nums,targer,mid,right);}} else {//左为顺序if (nums[left]<nums[mid]) {if (nums[mid]>targer&& nums[left]<targer) {return find(nums,targer,left,mid);} else {return find(nums,targer,mid,right);}} else {//右为顺序if (nums[mid]<targer&&nums[right]>targer) {return find(nums,targer,mid,right);} else {return find(nums,targer,left,mid);}}}}
这道题用无尽的while循环做比我这种递归的方式会好一点,至少空间占用少吧~即while(low
这篇关于leetcode解题方案--033--Search in Rotated Sorted Array的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!