码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Search in Rotated Sorted Array

时间:2015-11-27 10:45:14      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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

 

[LeetCode]Search in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/4999774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!