[LeetCode]Search in Rotated Sorted Array

Search in Rotated Sorted Array

My Submissions
Total Accepted: 76870 Total Submissions: 264831 Difficulty: Hard

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.

Subscribe to see which companies asked this question









這個題目曾經面試的時候遇到過,當時面試結果是萎了,做這道題目的時候才知道自己爲什麼萎了,這個題目需要考慮六種情況,分別是target和nums[mid]跟nums[0]比較。我當時只是用target跟nums[0]比較。

public class Solution {

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


}


發佈了232 篇原創文章 · 獲贊 17 · 訪問量 44萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章