leetcode_34——Search for a Range(二分查找)
2015-05-27 15:20
441 查看
Search for a Range
Total Accepted: 43717 Total Submissions: 158420My SubmissionsQuestion Solution
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].
Hide Tags
Array Binary Search
Have you met this question in a real interview?
Yes
No
Discuss
这道题直接采用二分查找就可以,只是有一点我没有接着做下去,就是第一次采用二分查找在已排好序的数列中找到那个数,其实还应该接着分别采用二分查找来找
那个两边的端点,但是由于直接已经可以AC了,所以我没有接着做下去了
#include<iostream> #include<vector> using namespace std; vector<int> searchRange(vector<int>& nums, int target) { int len=nums.size(); int i=0; int j=len; int flag=0; int locat; while(i!=j) { int z=(i+j)/2; if(nums[z]==target) {flag=1;locat=z;break;} if(target>nums[z]) i=z+1; else j=z; } vector<int> last_reault; if(flag==0) { last_reault.push_back(-1); last_reault.push_back(-1); } else { int a=locat,b=locat; for(int i=locat;i<len;i++) if(nums[i]==target) a=i; for(int j=locat;j>=0;j--) if(nums[j]==target) b=j; last_reault.push_back(b); last_reault.push_back(a); } return last_reault; } int main() { }
相关文章推荐
- [leetcode-二分查找]--34. 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(查找一个范围)
- 34. Search for a Range(二分查找有重复元素数组中的目标数的第一个位置和最后一个位置)
- Leetcode 34 Search for a Range (二分搜索 lower_bound和upper_bound)
- LeetCode-----34. Search for a Range(查找范围)
- leetcode 二分查找 Search for a Range
- LeetCode 34 Search for a Range (有序数组中查找给定数字的起止下标)
- leetcode:Search for a Range(数组,二分查找)
- leetcode-二分查找:Search for a range
- LeetCode 34. Search for a Range(有序数组,查找给定值范围)
- leetcode:Search for a Range 二分查找
- leetCode_Search for a Range(二分查找)
- [leetcode] 【查找】 34. Search for a Range
- LeetCode-Search for a Range-搜索范围-二分查找
- leetcode Add to List 34. Search for a Range 二分查找
- LeetCode:Search Insert Position,Search for a Range (二分查找,lower_bound,upper_bound)
- LeetCode 34 Search For A Range 二叉查找相关(二)