[LeetCode]Search in Rotated Sorted Array

来源:互联网 发布:淘宝卖玩具 编辑:程序博客网 时间:2024/05/04 20:27

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;    }}


0 0
原创粉丝点击