欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 33 Search in Rotated Sorted Array

程序员文章站 2022-07-16 11:56:53
...

Problem:

Leetcode 33 Search in Rotated Sorted Array

Analysis:

Leetcode 33 Search in Rotated Sorted Array

This question can be transferred as the above figure.
two scenarios: which represent by mid1 and mid2.

Leetcode 33 Search in Rotated Sorted Array

Code:

public int search(int[] nums, int target) {
		 
		 if (nums.length == 0 || nums == null) {
				return -1;
			}
		 
		 int left = 0, right = nums.length - 1;
		 while(left <= right) {
			 int mid = (left + right) / 2;
			 if (nums[mid] == target) {
					return mid;
			 }else if (nums[mid] < nums[left]) {
				 
				 if (nums[mid] < target && nums[right] >= target) {
						left = mid + 1;
					}else {
						right = mid -1;
					}			 
			 }else {
				 if (nums[left] <= target && nums[mid] > target) {
						right = mid - 1;
					}else {
						left = mid + 1;
					}
			 }	 
		 }	 
		 return -1;
	 }