leetcode34题理解--二分(特殊利用判等条件)

 

题目: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].

 

 

我的解决办法:

 

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] ret = new int[] { -1, -1 };
		int h = nums.length - 1;
		int l = 0;
		int m;
		while (h >= l) {
			m = (h + l) / 2;

			if (nums[m] > target) {
				h = m - 1;
			}
			if (nums[m] < target) {
				l = m + 1;
			}
			if (nums[m] == target) {
				for (int i = l; i <= m; i++) {
					if (nums[i] == target) {
						ret[0] = i;
						break;
					}
				}
				for (int i = m; i <= h; i++) {
					if(nums[h]==target){
						ret[1]=h;
						break;
						
					}
					if (nums[i] != target) {
						ret[1] = i-1;
						break;
					}
				}
				return ret;
				
			}
		}

		return ret;
    }
}

显然没有很好的理解二分查找的概念

 

二分查找算法是基于有序序列的查找算法,时间复杂度为O(logn)

 

int[] ret = new int[] { -1, -1 };
		if(nums.length==0){
			return ret;
		}
		
		int h = nums.length - 1;
		int l = 0;
		if(target<nums[l]||target>nums[h]){
			return ret;
			
		}		
		int m;
		while (h >l) {
			m=(h+l)/2;
			if(nums[m]<target){
				l=m+1;
			}else{
				h=m;
			}			
		}
		if(nums[l]!=target){
			return ret;
		}else{
			ret[0]=l;
		}
		
		 h = nums.length - 1;
		 l = 0;
		while (h > l) {
			m=(h+l)/2;
			if(nums[m]<=target){
				l=m+1;
			}else{
				h=m;
			}			
		}
		if(nums[l]==target){
			ret[1]=l;
		}else{
			ret[1]=l-1;
		}

		return ret;

在一本书上找到了一个模板

 

 

public int solve(int left,int right){
		int mid;		
		while(left<right){//对于[left,right]来说,left==right 意味着找到唯一的的位置
			mid =(left+right)/2;
			if(条件成立){
				right=mid;
			}else{
				left=mid+1;
			}
		}
		return left;
	}


真正大的理解这个,可以画一张图更好的理解

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值