LintCode:搜索旋转排序数组

来源:互联网 发布:58网络销售怎么样 编辑:程序博客网 时间:2024/06/07 19:58
假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。
你可以假设数组中不存在重复的元素。
您在真实的面试中是否遇到过这个题? 
Yes
样例

给出[4, 5, 1, 2, 3]和target=1,返回 2

给出[4, 5, 1, 2, 3]和target=0,返回 -1

标签 Expand  

相关题目 Expand 
解题思路:
2分搜索
http://www.code123.cc/docs/leetcode-notes/binary_search/search_in_rotated_sorted_array.html
notes/binary_search/search_in_rotated_sorted_array.html
public class Solution {    /**     *@param A : an integer rotated sorted array     *@param target :  an integer to be searched     *return : an integer     */    public int search(int[] A, int target) {        // write your code here          if (A == null || 0 == A.length)               return -1;          int left = 0;          int right = A.length - 1;          int mid = -1;          while (left < right - 1) {               mid = (left + right) / 2;               if (target == A[mid]) {                    return mid;               }               if (A[left] < A[mid]) {                    if (A[left] <= target && A[mid] >= target) {                         right = mid;                    } else {                         left = mid;                    }               } else {                    if (A[mid] <= target && A[right] >= target ) {                         left = mid;                    } else {                         right = mid;                    }               }          }          if (target == A[left]) {               return left;          } else if (target == A[right]) {               return right;          } else {               return -1;          }    }}





0 0
原创粉丝点击