设为首页 加入收藏

TOP

LeetCode Search for a Range
2015-07-20 17:16:24 来源: 作者: 【 】 浏览:2
Tags:LeetCode Search for Range

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
  
    searchRange(int A[], int n, int target) {
			int left = 0, right = n;
			while (left < right) {
				int mid = left + right >> 1;
				if (A[mid] >= target) 
					right = mid;
				else left = mid + 1;
			}
			int ansLeft = left;

			left = 0, right = n;
			while (left < right) {
				int mid = left + right >> 1;
				if (A[mid] > target)
					right = mid;
				else left = mid + 1;
			}

			if (A[ansLeft] != target)
				return vector
   
    {-1, -1}; else return vector
    
     {ansLeft, left-1}; } };
    
   
  




】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Fliptile poj 3279 开关问题 下一篇POJ1087A Plug for UNIX(会议室的..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·怎样用 Python 写一 (2025-12-27 02:49:19)
·如何学习python数据 (2025-12-27 02:49:16)
·想要自学数据分析, (2025-12-27 02:49:14)
·Java 集合框架 - 菜 (2025-12-27 02:19:36)
·Java集合框架最全详 (2025-12-27 02:19:33)