[leetcode]Search in Rotated Sorted Array

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   ar   

Search in Rotated Sorted Array

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.

二分尋找的變形

演算法思路:

a[mid] == target return mid;

a[mid] < target 分為兩種情況

1. a[mid]和target在同半邊,begin = mid + 1

2. a[mid]和target在不同的半邊,則a[mid]肯定在後面,target在前半邊,因此往前找end = mid - 1;

a[mid] > target同理

1. a[mid]和target在同半邊,end = mid - 1;

2. a[mid]和target在不同的半邊,則a[mid]肯定在前面,target在後半邊,因此往前找begin = mid + 1;

代碼如下:

 1 public class Solution { 2     public int search(int[] a, int target) { 3          if(a == null || a.length == 0) return -1; 4             int begin = 0, end = a.length - 1; 5             while(begin <= end){ 6                 int mid = (begin + end) >> 1; 7                 if(a[mid] == target){ 8                     return mid; 9                 }else if(a[mid] < target){10                     if(a[mid] < a[begin] && target >= a[begin]){11                         end = mid - 1;12                     }else{13                         begin = mid + 1;14                     }15                 }else{16                     if(a[mid] >= a[begin] && target < a[begin]){17                         begin = mid + 1;18                     }else{19                         end = mid - 1;20                     }21                 }22             }23             return -1;24      }25 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.