34 Search for a Range

原创 2016年05月31日 22:25:45

利用原数组中的元素是有序的,对数组进行二分,例如Given [5, 7, 7, 8, 8, 10] and target value 8,


若找到的序列ele[lo]==ele[hi]&&ele[lo]==target,说明这[lo,hi]区间的元素都为target,二分的结果有四种


1. 左边找到+右边找到,因为数组有序,找到的区间一定相邻! 这时候合并一下取 left=左边left ,right=右边right即可。


2. 左边找到+右边没找到,返回左边区间


3. 左边没找到+右边找到,返回右边区间


4. 左边没找到+右边没找到,返回[-1,-1]


注意以上情况均为迭代处理。


public int[] searchRange(int[] nums, int target)
	{
		return searchaux(nums, target, 0, nums.length-1);
		
	}
	
	public int[] searchaux(int[] nums,int target,int lo,int hi)
	{
		if(nums[lo]==nums[hi]&&nums[lo]==target)
			return new int[] {lo,hi};
		if(lo==hi)
			return new int[] {-1,-1};
		
		int mid=(lo+hi)>>1;
		int[] lret=searchaux(nums, target, lo, mid);
		int[] rret=searchaux(nums, target, mid+1, hi);
		
		int leftindex=-1;
		int rightindex=-1;
		if(lret[0]>=0&&rret[0]>=0)
			{
				leftindex=lret[0];
				rightindex=rret[1];
			}
		else if(lret[0]>=0)
		{
			leftindex=lret[0];
			rightindex=lret[1];
		}
		else if(rret[0]>=0)
		{
			leftindex=rret[0];
			rightindex=rret[1];
		}
		return new int[] {leftindex,rightindex};
		
		
	}


版权声明:本文为博主原创文章,未经博主允许【可以】转载

leetcode-34 Search for a Range

这破题,把我弄的心烦意乱,就是三次折半,不过后两次有些特殊 class Solution { public: vector searchRange(int A[], int n, int t...
  • sole_cc
  • sole_cc
  • 2015年04月14日 15:22
  • 321

Leetcode-34. Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value. Yo...
  • mcf171
  • mcf171
  • 2016年10月03日 20:11
  • 142

[LeetCode] Search for a Range [34]

题目 Given a sorted array of integers, find the starting and ending position of a given target value. ...
  • swagle
  • swagle
  • 2014年06月13日 11:14
  • 969

[leetcode]34. Search for a Range(Java实现)

leetcode测试地址:https://leetcode.com/problems/search-for-a-range/#/description Given an array ...

[LeetCode]34.Search for a Range

【题目】 Given a sorted array of integers, find the starting and ending position of a given target val...

Leetcode NO.34 Search for a Range

题目要求如下: Given a sorted array of integers, find the starting and ending position of a given targ...

<LeetCode OJ> 34. Search for a Range

34. Search for a Range My Submissions Question Total Accepted: 75021 Total Submissions: 261472 D...

[LeetCode-Java]34. Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value.Your...

【LeetCode OJ 34】Search for a Range

题目链接:https://leetcode.com/problems/search-for-a-range/ 题目:Given a sorted array of integers, find th...

LeetCode_34---Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value. Yo...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:34 Search for a Range
举报原因:
原因补充:

(最多只允许输入30个字)