leetcode——34——Search for a Range
来源:互联网 发布:rational rose mac 编辑:程序博客网 时间:2024/06/06 15:44
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]
.
自己写的代码,没有真正的实现二分查找,运行速度相对较慢
class Solution {public:vector<int> searchRange(vector<int>& nums, int target) {int i = 0;int j = nums.size() - 1;int mid;vector<int> res;while (i <= j){mid = i + (j - i) / 2;if (nums[mid] > target){j = mid - 1;}else if (nums[mid] < target){i = mid + 1;}else{ int m = mid, n = mid;while (nums[m] == target&&nums[m+1] ==target&&m<nums.size()-1){m++;}while (nums[n] == target&&nums[n-1] == target&&n>0){n--;}res.push_back(n);res.push_back(m);return res;}}res.push_back(-1);res.push_back(-1);return res;}};
完全实现二分查找的代码
class Solution {public:vector<int> searchRange(vector<int>& nums, int target) {vector<int> res(2, -1); if(nums.empty()) return res; int high = binarySearchUp(nums, target, 0, nums.size() -1); int low = binarySearchLow(nums, target, 0, nums.size() - 1); if(high >= low) { res[0] = low; res[1] = high; return res; } return res;}private: int binarySearchLow(vector<int>& nums, int target, int begin, int end) { if(begin > end) return begin; int mid = begin + (end - begin) / 2; if(nums[mid] < target) return binarySearchLow(nums, target, mid + 1, end); else return binarySearchLow(nums, target, begin, mid - 1); } int binarySearchUp(vector<int>& nums, int target, int begin, int end) { if(begin > end) return end; int mid = begin + (end - begin) / 2; if(nums[mid] > target) return binarySearchUp(nums, target, begin, mid - 1); else return binarySearchUp(nums, target, mid + 1, end); }};
0 0
- 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——34——Search for a Range
- 【leetcode】Array——Search for a Range(34)
- <34>——Search for a Range
- leetcode 034 —— Search for a Range
- LeetCode题解——Search for a Range
- Leetcode——34. Search for a Range
- LeetCode 之 Search for a Range — C++ 实现
- LeetCode34——Search for a Range
- Algorithms—34.Search for a Range
- LeetCode 34 — Search for a Range(C++ Java Python)
- leetcode——Search for a Range 排序数组中寻找目标下标范围(AC)
- leetcode——Search for a Range 二分查找重复数字
- Leetcode刷题记——34. Search for a Range(查找一个范围)
- solr与tomcat搭建
- java实现金钱加千位符
- 宏定义中的do...while(0)
- java中finally关键字
- ThreadLoacl的作用及使用
- leetcode——34——Search for a Range
- 关于通过Uri 查询文件路径的问题
- Java的数据类型
- 基于bootstrap实现简单用户管理功能
- Android注解式绑定控件,没你想象的那么难
- centos6.7 安装端口映射工具 rinetd
- 自己抄写的课本上的代码,暂时还是搞不懂什么意思,先留着,以后再好好看看
- Github-git pull解决远程与本地仓库的冲突
- 类与对象(3)继承,重载,覆盖