leetcode_34_Search for a Range

来源:互联网 发布:兄弟连it教育怎么样 编辑:程序博客网 时间:2024/06/02 03:57

欢迎转载,如有错误或疑问请留言纠正,谢谢微笑


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].


//vs2012测试代码//Binary Search//we must know how to process the 3 cases below://1.how to find the right most target//2.how to find the left most target//3.how to find the insert position#include<iostream>#include<vector>using namespace std;#define N 6class Solution {public:    vector<int> searchRange(int A[], int n, int target) {        vector<int> ans(2);if(n==0)return vector<int>( 2,-1 );int left = 0 , right = n-1;while( left<=right ){int mid = left + (right-left)/2;if( A[mid] >= target)  //find the left most targetright = mid-1;else if (A[mid] < target)left = mid+1;}int target_left = left;left=0 , right=n-1;while( left<=right ){int mid = left + (right-left)/2;if(A[mid] <= target) //find the right most targetleft = mid +1;else if ( A[mid] > target)right = mid -1;}int target_right = right;if( A[target_left]!=target || A[target_right]!=target)return vector<int>( 2,-1 );ans[0] = target_left;ans[1] = target_right;return ans;    }};int main(){int a,target;int A[N];vector<int> ans(2);for(int i=0; i<N; i++){cin>>a;A[i]=a;}cin>>target;Solution lin;ans = lin.searchRange( A,N,target);for(int i=0; i<2; i++)cout<<ans[i];cout<<endl;}



//方法一:自测Accepted//Binary Search//we must know how to process the 3 cases below://1.how to find the right most target//2.how to find the left most target//3.how to find the insert positionclass Solution {public:    vector<int> searchRange(int A[], int n, int target) {        vector<int> ans(2);if(n==0)return vector<int>( 2,-1 );int left = 0 , right = n-1;while( left<=right ){int mid = left + (right-left)/2;if( A[mid] >= target)  //find the left most targetright = mid-1;else if (A[mid] < target)left = mid+1;}int target_left = left;left=0 , right=n-1;while( left<=right ){int mid = left + (right-left)/2;if(A[mid] <= target) //find the right most targetleft = mid +1;else if ( A[mid] > target)right = mid -1;}int target_right = right;if( A[target_left]!=target || A[target_right]!=target)return vector<int>( 2,-1 );ans[0] = target_left;ans[1] = target_right;return ans;    }};



1 0
原创粉丝点击