First Position of Target
First Position of Target
给你一个排序好的数组 之后给你一个数字返回第一个出现的数组位置的下标 要求O(log n)
For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.
If the target number does not exist in the array, return -1.
Example
If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.
首先想到的肯定就是二分 因为数组有序
1 class Solution{ 2 public: 3 int binarySearch(std::vector<int> &array,int target){ 4 int l = 0; 5 int r = array.size()-1; 6 int mid; 7 while(l<=r){ 8 mid =l+(r-l)/2; 9 if(target==array[mid]){ 10 if(mid==0) 11 return mid; 12 } 13 else if (array[mid]!=array[mid-1]) 14 { 15 return mid; 16 } 17 else{ 18 r = mid -1; 19 } 20 else if(target<array[mid]){ 21 r=mid+1; 22 } 23 else{ 24 l = mid+1; 25 } 26 } 27 return -1; 28 } 29 };
Stay Hungry Stay Foolish.