Leetcode[81]-Search for a Range
2015-06-11 10:36
429 查看
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].
思路:首先初始化一个2列的数组,值为-1,然后一次遍历数组,设置一个变量作为标识,记录出现target值的下标,并保存到数组中,如果标识值等于=了,就不增加它的值,保证数组第二个元素是最后一个出现target的下标。
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].
思路:首先初始化一个2列的数组,值为-1,然后一次遍历数组,设置一个变量作为标识,记录出现target值的下标,并保存到数组中,如果标识值等于=了,就不增加它的值,保证数组第二个元素是最后一个出现target的下标。
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> res(2); res[0]=-1,res[1]=-1; int n = nums.size(); int temp = 0; for(int i = 0; i < n; i++){ if(target == nums[i]){ if(temp == 2) res[temp-1] = i; else res[temp++] = i; } } if(temp ==1) { res[temp] = res[0]; } return res; } };
相关文章推荐
- 6.11
- 【Leetcode Algorithm】Remove Nth Node From End of List
- 血流动力学相关概念和定律
- 也来开个博客,分享一下我掉过的坑!
- spring注解介紹
- 社説 20150611 GPS捜査 位置情報を適切に活用したい
- 微软100题(77)链表的题目
- Java中的移位操作以及基本数据类型转换成字节数组【收集】
- Shell脚本变量定义
- Excel Sheet Column Title&&Excel Sheet Column Number
- Linux启动报错UNEXPECTED INCONSISTENCY; RUN FSCK MANUALLY
- Python正则表达式
- 15个SAT数学高分公式介绍
- xloadtree实现web动态目录树(分层加载)
- 一篇读懂CSS布局模型
- 日经社説 20150611 訪日外国人の増加へ規制緩和の加速を
- Hangover
- mysql ERROR 1025 (HY000): Error on rename of
- xloadtree实现web动态目录树(分层加载)
- 83款 网络爬虫开源软件