算法分析与设计课程——LeetCode刷题之Search for a Range
2018-01-11 22:10
519 查看
题目:
Given an array of integers sorted in ascending order, 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
For example,
Given
return
答案:
vector<int> searchRange(vector<int>& nums, int target) {
int idx1 = lower_bound(nums, target);
int idx2 = lower_bound(nums, target+1)-1;
if (idx1 < nums.size() && nums[idx1] == target)
return {idx1, idx2};
else
return {-1, -1};
}
int lower_bound(vector<int>& nums, int target) {
int l = 0, r = nums.size()-1;
while (l <= r) {
int mid = (r-l)/2+l;
if (nums[mid] < target)
l = mid+1;
else
r = mid-1;
}
return l;
}
Given an array of integers sorted in ascending order, 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].
答案:
vector<int> searchRange(vector<int>& nums, int target) {
int idx1 = lower_bound(nums, target);
int idx2 = lower_bound(nums, target+1)-1;
if (idx1 < nums.size() && nums[idx1] == target)
return {idx1, idx2};
else
return {-1, -1};
}
int lower_bound(vector<int>& nums, int target) {
int l = 0, r = nums.size()-1;
while (l <= r) {
int mid = (r-l)/2+l;
if (nums[mid] < target)
l = mid+1;
else
r = mid-1;
}
return l;
}
相关文章推荐
- 算法分析与设计课程(5):【leetcode】Search for a Range
- 第九周算法分析与设计: Search for a Range
- 算法分析与设计课程——LeetCode刷题之 Spiral Matrix
- 算法分析与设计课程(4):【leetcode】Wildcard Matching
- 算法分析与设计课程——LeetCode刷题之4Sum
- 算法分析与设计课程——LeetCode刷题之Merge Two Sorted Lists
- 算法分析与设计课程(11):【leetcode】Gray Code
- 【LeetCode-面试算法经典-Java实现】【034-Search for a Range(搜索一个范围)】
- 算法分析与设计课程——LeetCode刷题之 Pow(x, n)
- 算法分析与设计课程——LeetCode刷题之Reverse Integer
- 算法分析与设计——LeetCode Problem.598 Range Addition II
- 算法分析与设计课程(15):【leetcode】 Find Minimum in Rotated Sorted Array
- 算法分析与设计课程——LeetCode刷题之Valid Parentheses
- 算法分析与设计课程(10):【leetcode】Simplify Path
- 算法分析与设计——LeetCode Problem.33 Search in Rotated Sorted Array
- 算法分析与设计课程(14):【leetcode】 Maximal Square
- 算法分析与设计课程——LeetCode刷题之 Rotate Image
- 算法分析与设计——LeetCode Problem.35 Search Insert Position
- 算法分析与设计课程(17):【leetcode】4Sum
- [算法分析与设计] leetcode 每周一题: Validate Binary Search Tree