首页 > 学院 > 开发设计 > 正文

LeetCode-SearchinRotatedSortedArray

2019-11-14 14:54:03
字体:
来源:转载
供稿:网友

题目:

Search in Rotated Sorted Array
Total Accepted: 81090 Total Submissions: 277272 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.

思路:

数组被翻转,我们以中间元素为核心,把它分为两种情况,一种情况是中间元素的左边是有序的,一种是中间元素的右边是有序的。比如{ 0 1 2 4 5 6 7 }被翻转为{ 6 7 0 1 2 4 5 }或{ 2 4 5 6 7 0 1 }。

所以每次判断我们都取轻避重,总是跟有序的这边比较。

package array;public class SearchInRotatedSortedArray {    public int search(int[] nums, int target) {        int len = 0;        if (nums == null || (len = nums.length) == 0) return 0;        // { 0 1 2 4 5 6 7 }        // 1. { 6 7 0 1 2 4 5 }        // 2. { 2 4 5 6 7 0 1 }        int l = 0;        int r = len - 1;                while (l <= r) {            int mid = (l + r) / 2;            if (nums[mid] == target) return mid;            if (nums[mid] < nums[r]) {                if (target > nums[mid] && target <= nums[r])                    l = mid + 1;                else                    r = mid - 1;            } else {                if (nums[l] <= target && target < nums[mid])                     r = mid - 1;                else                    l = mid + 1;            }        }                return -1;    }        public static void main(String[] args) {        // TODO Auto-generated method stub        int[] nums = { 4, 5, 6, 7, 0, 1, 2 };        SearchInRotatedSortedArray s = new SearchInRotatedSortedArray();        System.out.PRintln(s.search(nums, 2));    }}

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表