LeetCode 之 Search for a Range
来源:互联网 发布:户外轨迹软件 编辑:程序博客网 时间:2024/03/29 20:55
原题:
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首先用一个递归来进行,判断start是否比end大,若大于则return(要注意不是>=,因为在等于的情况时,还没有判断这个A[start](或A[end]), 因此在等于的时候会继续进行循环 );
2若中间值不等于target,就分别查找左一半和右一半数组
代码如下(68 ms):
class Solution {public: vector<int> searchRange(int A[], int n, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<int> result; result.push_back(-1); result.push_back(-1); //把result传下去,方便返回最后结果 search(A,0,n-1, target , result); return result; } void search(int A[] , int start , int end , int target , vector<int>&result){ //返回 if(start > end){ return; } if(A[(start+end)/2] == target){ //中间的值和target相等,向前找最小的index放在result[0]中 for(int i = (start+end)/2 ; i>=0 ;i--){ if(A[i]==target){ result[0]=i; } else{ break; } } //中间的值和target相等,向前找最大的index放在result[1]中 for(int i = (start+end)/2 ; i<= end ;i++){ if(A[i]==target){ result[1]=i; } else{ break; } } return; } //找左边的 else if(A[(start+end)/2] > target ) search( A, start , (start+end)/2 -1 , target , result); //找右边的 else search( A, (start+end)/2 +1 , end , target ,result); }};
- leetcode之Search for a Range
- LeetCode 之 Search for a Range
- LeetCode之Search for a Range
- leetcode之Search for a Range
- LeetCode之Search for a Range
- leetcode之Search for a Range
- 【Leetcode】之Search for a Range
- leetcode之search for a range
- LeetCode 之 Search for a Range
- Leetcode之Search for a Range
- Leetcode之Search for a Range 问题
- LeetCode: Search for a Range
- LeetCode Search for a Range
- [Leetcode] Search for a Range
- LeetCode : Search for a Range
- [LeetCode] Search for a Range
- [Leetcode] Search for a Range
- Leetcode Search for a Range
- “窗口类、窗口类的对象和窗口”三者的关系
- 【C++自绘控件】如何用GDI+来显示图片
- STM32 Flash 擦除 读写 成功
- Spring MVC 教程,快速入门,深入分析
- 使用绑定变量
- LeetCode 之 Search for a Range
- mongodb集成spring
- mongodb分布式集群架构
- python 获取当前脚本所在路径
- VC++操作word
- poj2407 Relatives 欧拉函数基本应用
- Remove Nth Node From End of List
- Polygon获取中心点坐标
- 【C++】容器list的用法