[LeetCode] Search for a Range [34]
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] Search for a Range [34]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
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].
原題鏈接(點我)
解題思路
查找一個數出現的范圍,給一個排好序的數組和一個數,找出這個數在數組中出現的范圍。
這個題直接使用一次遍歷就能夠得到結果,這種時間復雜度為O(n)。可是對于有序數組我們一般能夠使用二分查找能夠得到更好的O(logn)的時間復雜度。我們能夠使用二分查找找到這個數第一次出現的位置和這個數最后一次出現的位置,這樣就能夠得到它出現的區間。
代碼實現
class Solution { public:vector<int> searchRange(int A[], int n, int target) {vector<int> ret;if(A==NULL || n<=0) return ret;int first = getFirst(A, n, target);int last = getLast(A, n, target);ret.push_back(first);ret.push_back(last);return ret;}int getFirst(int A[], int n, int target){int begin = 0, end = n-1;int mid;while(begin<=end){int mid = (begin+end)/2;if(A[mid] == target){if(mid==0 || A[mid-1]<A[mid])return mid;elseend = mid-1;}else if(A[mid] < target)begin = mid+1;elseend = mid-1;}return -1;}int getLast(int A[], int n, int target){int begin = 0, end = n-1;int mid;while(begin<=end){int mid = (begin+end)/2;if(A[mid] == target){if(mid==n-1 || A[mid+1]>A[mid])return mid;elsebegin = mid+1;}else if(A[mid] < target)begin = mid+1;elseend = mid-1;}return -1;} };假設你認為本篇對你有收獲,請幫頂。
另外,我開通了微信公眾號--分享技術之美,我會不定期的分享一些我學習的東西. 你能夠搜索公眾號:swalge?或者掃描下方二維碼關注我
(轉載文章請注明出處:?http://blog.csdn.net/swagle/article/details/30466235 )
轉載于:https://www.cnblogs.com/mfrbuaa/p/3948216.html
總結
以上是生活随笔為你收集整理的[LeetCode] Search for a Range [34]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python实现微信自动发信息软件_Py
- 下一篇: 传Facebook将推出应用中心挑战谷歌