33.在旋转排序的数组中查找某值位置

来源:互联网 发布:java流行框架2017 编辑:程序博客网 时间:2024/06/07 01:35

Search in Rotated Sorted Array

问题描述;

Suppose an array sorted in ascending order 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.

知识补充:

测试代码:

    int search(vector<int>& nums, int target) {        for(int i=0;i<nums.size();i++)        {            if(nums[i]==target)            {                return i;            }        }        return -1;    }

性能:

这里写图片描述

参考答案:

    int lo = 0;    int hi = A.length - 1;    while (lo < hi) {        int mid = (lo + hi) / 2;        if (A[mid] == target) return mid;        if (A[lo] <= A[mid]) {            if (target >= A[lo] && target < A[mid]) {                hi = mid - 1;            } else {                lo = mid + 1;            }        } else {            if (target > A[mid] && target <= A[hi]) {                lo = mid + 1;            } else {                hi = mid - 1;            }        }    }    return A[lo] == target ? lo : -1;

性能:

这里写图片描述

阅读全文
0 0