标签:
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]
.
方法1:不使用二分
1 class Solution { 2 public: 3 vector<int> searchRange(vector<int>& nums, int target) { 4 vector<int> ans(2); 5 if(nums.size() == 0) return ans; 6 int i = 0; 7 int j = nums.size()-1; 8 while(i <=j ) 9 { 10 while(i <= j && nums[i] != target) 11 { 12 ++i; 13 } 14 while(i <= j && nums[j] != target) 15 { 16 --j; 17 } 18 if(i<=j) 19 { 20 ans[0] = i; 21 ans[1] = j; 22 return ans; 23 } 24 } 25 ans[0] = -1; 26 ans[1] = -1; 27 return ans; 28 } 29 };
方法二:标准二分
参见博客:http://www.tuicool.com/articles/FV3Ure 总结的非常好
1 class Solution { 2 public: 3 vector<int> searchRange(vector<int>& nums, int target) { 4 vector<int> ans(2,-1); 5 if (nums.size() == 0) { 6 return ans; 7 } 8 9 int len = nums.size(); 10 int left = 0; 11 int right = len - 1; 12 13 // so when loop end, there will be 2 elements in the array. 14 // search the left bound. 15 while (left < right - 1) { 16 int mid = left + (right - left) / 2; 17 if (target == nums[mid]) { 18 // 如果相等,继续往左寻找边界 19 right = mid; 20 } else if (target > nums[mid]) { 21 // move right; 22 left = mid; 23 } else { 24 right = mid; 25 } 26 } 27 28 if (nums[left] == target) { 29 ans[0] = left; 30 } else if (nums[right] == target) { 31 ans[0] = right; 32 } else { 33 return ans; 34 } 35 36 left = 0; 37 right = len - 1; 38 // so when loop end, there will be 2 elements in the array. 39 // search the right bound. 40 while (left < right - 1) { 41 int mid = left + (right - left) / 2; 42 if (target == nums[mid]) { 43 // 如果相等,继续往右寻找右边界 44 left = mid; 45 } else if (target > nums[mid]) { 46 // move right; 47 left = mid; 48 } else { 49 right = mid; 50 } 51 } 52 53 if (nums[right] == target) { 54 ans[1] = right; 55 } else if (nums[left] == target) { 56 ans[1] = left; 57 } else { 58 return ans; 59 } 60 61 return ans; 62 } 63 }; 64
标签:
原文地址:http://www.cnblogs.com/chdxiaoming/p/4757980.html