LeetCode Search for a Range (二分查找)
2016-09-20 18:16
477 查看
题意
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].
给定一个有序数组和一个目标值,查找出目标值在数组中出现的发生下标区域。时间复杂度要求log(N)。
解法
刚开始以为下标也需要用二分来查找,但看讨论发现大家都是找出目标值然后再向两边搜索-_-b,这样做的话,最差的情况下(数组里的数全都一样)就是O(N)了,但是也能过。class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int left = 0; int right = nums.size() - 1; int index_a = -1; int index_b = -1; int index = 0; bool flag = false; while(left <= right) { int mid = (left + right) >> 1; if(nums[mid] == target) { flag = true; index = mid; break; } else if(nums[mid] < target) left = mid + 1; else right = mid - 1; } if(flag) index_a = index; while(index_a >= 1 && nums[index_a - 1] == target) index_a --; if(flag) index_b = index; while(index_b < nums.size() - 1 && nums[index_b + 1] == target) index_b ++; vector<int> rt = {index_a,index_b}; return rt; } };
相关文章推荐
- leetcode-二分查找:Search for a range
- leetcode 34. Search for a Range 二分查找
- leetcode 二分查找 Search for a Range
- leetcode:Search for a Range(数组,二分查找)
- LeetCode:Search Insert Position,Search for a Range (二分查找,lower_bound,upper_bound)
- leetcode:Search for a Range 二分查找
- leetcode_34——Search for a Range(二分查找)
- [leetcode-二分查找]--34. Search for a Range
- leetCode_Search for a Range(二分查找)
- leetcode 34. Search for a Range (二分查找)
- LeetCode-Search for a Range-搜索范围-二分查找
- 34.leetcode Search for a Range(meidum)[二分查找]
- 二分查找之Search for a Range
- Leetcode 34 Search for a Range (二分搜索 lower_bound和upper_bound)
- 【二分查找】Search for a Range
- 二分查找:Search for a Range
- 34. Search for a Range(二分查找有重复元素数组中的目标数的第一个位置和最后一个位置)
- [leetcode] 【查找】 34. Search for a Range
- LeetCode 34 Search for a Range (有序数组中查找给定数字的起止下标)
- Search for a Range——稍微升级版的二分查找