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

【Leetcode】Search in Rotated Sorted Array II

时间:2016-05-27 12:29:39      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/

题目:
Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

思路:
找到逆序的位置,然后根据该位置将数组分为两半,分别二分查找

算法:

    public boolean search(int[] nums, int target) {
        int index = 0; // 找到旋转点即逆序的点
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] > nums[i + 1]) {
                index = i;
            }
        }
        boolean left_res = search(nums, target, 0, index);
        boolean right_res = search(nums, target, index + 1, nums.length - 1);
        return left_res || right_res;
    }

    public boolean search(int nums[], int target, int start, int end) {
        int left = start, right = end, mid = 0;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return true;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return false;
    }

【Leetcode】Search in Rotated Sorted Array II

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51493496

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