【leetcode】Search for a Range

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm‘s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

 

題解:按照題目要求的時間複雜度,使用二分方法,設定私人兩個變數begin和end,記錄最終找到的range的範圍,在遞迴二分的過程中,如果找到了目標,根據此時target在數組中的下表不斷的縮小begin和擴大end,這樣最終begin和end就是最大的range範圍了。

主要步驟如下:

  1. 如果A[mid] == target,根據mid的值更新begin和end值。然後判斷左邊數組最右邊的元素是否仍然和target相等,如果相等要繼續二分搜尋左邊的數組;右邊的數組也要做同樣的處理;
  2. 如果A[mid] < target,遞迴搜尋右邊的數組;
  3. 如果A[mid] > target,遞迴搜尋左邊的數組;

數組[2,2,2,2]的搜尋過程如下:

所以最終返回的range是[0,2]。

代碼如下:

 1 public class Solution { 2     private int begin; 3     private int end; 4     public void BinarySearch(int[] A,int target,int s,int e){ 5         if(s > e) 6             return; 7         int mid = s + (e - s)/2; 8         if(target == A[mid]){ 9             if(mid < begin)10                 begin = mid;11             if(mid > end)12                 end = mid;13             if(mid - 1>=0 && A[mid-1] == target)14                 BinarySearch(A, target, s, mid-1);15             if(mid + 1 < A.length && A[mid+1] == target)16                 BinarySearch(A, target, mid+1, e);17         }18         else{19             if(A[mid] > target)20                 BinarySearch(A, target, s, mid-1);21             else {22                 BinarySearch(A, target, mid+1, e);23             }24         }25     }26     public int[] searchRange(int[] A, int target) {27         begin = A.length;28         end = -1;29         BinarySearch(A, target, 0, A.length-1);30         31         int[] answer = new int[2];32         if(begin == A.length && end == -1){33             answer[0] = answer[1] = -1;34         }35         else{36             answer[0] = begin;37             answer[1] = end;38         }39         return answer;40     }41 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.