7.1—查找—Sear for a Range
来源:互联网 发布:儿童初学画画软件 编辑:程序博客网 时间:2024/06/04 01:24
描述
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].
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].
#include<iostream>using namespace std;int SearchforRange1(int a[],int n,int k){int res = -1;if (n <= 0)return res;int begin = 0; int end = n - 1;while (begin <= end){int mid = (begin + end) / 2;if (a[mid] < k){begin = mid + 1;}else if (a[mid] > k){end = mid - 1;}else{if ((mid-1)<0||a[mid - 1] < k){res = mid;return res;}else{end = mid - 1;}}}return res;}int SearchforRange2(int a[], int n, int k){int res = -1;if (n <= 0)return res;int begin = 0; int end = n - 1;while (begin <= end){int mid = (begin + end) / 2;if (a[mid] < k){begin = mid + 1;}else if (a[mid] > k){end = mid - 1;}else{if ((mid+1)>=n||a[mid + 1] > k){res = mid;return res;}else{begin = mid + 1;}}}return res;}int main(){const int n = 10;int a[n] = { 1, 3, 4, 5, 5, 5, 5, 7, 8, 10 };int k = 1;int begin = SearchforRange1(a, n, k);int end = SearchforRange2(a, n, k);cout << begin << " " << end<< endl;}
阅读全文
0 0
- 7.1—查找—Sear for a Range
- 7.3—查找—Sear a 2D Matrix
- 7.2—查找—Sear Insert Position
- 5.3.3—二叉查找树—Validate Binary Sear Tree
- 5.3.4—二叉查找树—Convert Sorted Array to Binary Sear Tree
- 5.3.5—二叉查找树—Convert Sorted List to Binary Sear Tree
- Leetcode 第7章 查找 7.1 search for a range
- leetcode——Search for a Range 二分查找重复数字
- Leetcode刷题记——34. Search for a Range(查找一个范围)
- [LeetCode]—Search for a Range 有序数组查找target的下标范围
- 【二分查找】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] 【查找】 34. Search for a Range
- 二分查找:Search for a Range
- 6.7—排序—Sort Colors
- 【基础算法练习】【最短路+图的遍历+最小生成树】水题 C+ E+ F-----AC题
- 迪杰斯特拉最短路径算法
- PAT 1002. A+B for Polynomials
- SpringMVC IOC DI接口版本管理(迭代版)
- 7.1—查找—Sear for a Range
- HDU 1535 Invitation Cards(多源点到单源点,dijkstra/spfa)
- 闲记
- typedef
- python 安装superset:error: Setup script exited with error: command 'gcc' failed with exit status 1
- 小白如何成长为优秀的系统设计专家?
- 7.2—查找—Sear Insert Position
- 剑指offer-39.二叉树的深度
- 关于日间夜间模式切换的一种实用方法