题解 | #在旋转过的有序数组中寻找目标值#
在旋转过的有序数组中寻找目标值
https://www.nowcoder.com/practice/87c0e7abcbda41e7963660fa7d020995
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @param target int整型 * @return int整型 */ public int search (int[] nums, int target) { // write code here int ret = -1; int left = 0; int right = nums.length - 1; int mid = (left + right) / 2; //分两种情况 if (nums[left] < nums[right]){ //1.数组为升序 while(left <= right){ mid = (left + right) / 2; if (nums[mid] < target){ left = mid + 1; }else if (nums[mid] > target){ right = mid - 1; }else if (nums[mid] == target){ ret = mid; break; } } }else{ //2.数组被旋转过 while(left <= right){ mid = (left + right) / 2; System.out.println(nums[mid]); if (nums[mid] < target){ if (target > nums[right]){ right = mid - 1; }else if (target < nums[right]){ left = mid + 1; }else if (target == nums[right]){ ret = right; break; } }else if (nums[mid] > target){ if (target > nums[left]){ right = mid - 1; }else if (target < nums[left]){ if (nums[mid] < nums[left]){ right = mid - 1; }else{ left = mid + 1; } }else if (target == nums[left]){ ret = left; break; } }else if (nums[mid] == target){ ret = mid; break; } } } return ret; } }