Leetcode 34 Search for a Range
Given an array of integers sorted in ascending order, 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]
.
解题思路:采用分治的思想对数组进行折半查找,这题重点在怎么找到target在数组的左端点的位置、右端点的位置,比如判断左端点就是找对应target的下标的前一个位置所对应的值,是否小于target;同理右端点也是这样思路,然后再分别判断一下各自边界条件是啥。
1 #include <stdio.h> 2 3 #include <vector> 4 5 int left_bound(std::vector<int>& nums, int target){ 6 int begin = 0; 7 int end = nums.size() - 1; 8 while(begin <= end){ 9 int mid = (begin + end) / 2; 10 if (target == nums[mid]){ 11 if (mid == 0 || nums[mid -1] < target){ 12 return mid; 13 } 14 end = mid - 1; 15 } 16 else if (target < nums[mid]){ 17 end = mid - 1; 18 } 19 else if (target > nums[mid]){ 20 begin = mid + 1; 21 } 22 } 23 return -1; 24 } 25 26 int right_bound(std::vector<int>& nums, int target){ 27 int begin = 0; 28 int end = nums.size() - 1; 29 while(begin <= end){ 30 int mid = (begin + end) / 2; 31 if (target == nums[mid]){ 32 if (mid == nums.size() - 1 || nums[mid + 1] > target){ 33 return mid; 34 } 35 begin = mid + 1; 36 } 37 else if (target < nums[mid]){ 38 end = mid - 1; 39 } 40 else if (target > nums[mid]){ 41 begin = mid + 1; 42 } 43 } 44 return -1; 45 } 46 47 class Solution { 48 public: 49 std::vector<int> searchRange(std::vector<int>& nums, int target) { 50 std::vector<int> result; 51 result.push_back(left_bound(nums, target)); 52 result.push_back(right_bound(nums, target)); 53 return result; 54 } 55 }; 56 57 int main(){ 58 int test[] = {5, 7, 7, 8, 8, 8, 8, 10}; 59 std::vector<int> nums; 60 Solution solve; 61 for (int i = 0; i < 8; i++){ 62 nums.push_back(test[i]); 63 } 64 for (int i = 0; i < 12; i++){ 65 std::vector<int> result = solve.searchRange(nums, i); 66 printf("%d : [%d, %d]\n",i , result[0], result[1]); 67 } 68 return 0; 69 }
通过~