67--71 二分查找

67 查找插入位置

力扣https://leetcode-cn.com/problems/N6YdxV/

func searchInsert(nums []int, target int) int {
	start:=0
	end:=len(nums)-1
	for start<=end{
		mid:=(start+end)/2
		if nums[mid]==target{
			return mid
		}else if nums[mid] >target{
			//target在mid的左边
			end = mid - 1
		}else{
			//target在mid的右边
			start = mid + 1
		}
	}
	return start
}

68 查找山峰顶部

力扣icon-default.png?t=LA92https://leetcode-cn.com/problems/B1IidL/

func peakIndexInMountainArray(arr []int) int {
	start:=0
	end:=len(arr)-1
	for start<=end{
		mid := (end-start)/2+start
		if mid-1<0{
			mid = 1
		}
		if mid +1 >=len(arr){
			mid = len(arr) - 2
		}

		if arr[mid-1]<arr[mid] && arr[mid+1]<arr[mid]{
			return mid
		}else if arr[mid-1]<arr[mid] && arr[mid+1]>arr[mid]{
			//峰顶在右边
			start = mid+1
		}else {
			//封顶在左边
			end = mid - 1
		}
	}
	return start
}

69 排序中只出现一次的数字

力扣icon-default.png?t=LA92https://leetcode-cn.com/problems/skFtm2/

func singleNonDuplicate(nums []int) int {
	length:=len(nums)
	start := 0
	end:=length -1
	for start<=end{
		mid := (end-start)/2+start
		if mid-1>=0&&nums[mid-1]==nums[mid]{
			if (end-mid)%2==0{
				//一次出现的在左边
				end = mid - 2
			}else {
				//一次出现的在右边
				start = mid + 1
			}
		}else if mid+1<length&&nums[mid+1]==nums[mid]{
			if (mid-start+1)%2==0{
				//一次出现的在左边
				end = mid-1
			}else {
				//一次出现的在右边
				start = mid + 2
			}
		}else{
			return nums[mid]
		}
	}
	return -1
}

70 求平方根

力扣icon-default.png?t=LA92https://leetcode-cn.com/problems/jJ0w9p/

func mySqrt(x int) int {
	start:=1
	end := x
	for start<=end{
		mid:=(end-start)/2 + start
		if mid<=x/mid{
			if mid+1 > x/(mid+1){
				return mid
			}
			start = mid +1
		}else {
			end = int(mid) - 1
		}
	}
	return 0
}

71 狒狒吃香蕉

力扣icon-default.png?t=LA92https://leetcode-cn.com/problems/nZZqjQ/

func getHours(piles []int,hours int)int{
	var sum int
	for i:=0;i<len(piles);i++{
		if piles[i]%hours ==0 {
			sum = sum + piles[i]/hours
		}else{
			sum = sum + piles[i]/hours + 1
		}
	}
	return sum
}


func minEatingSpeed(piles []int, h int) int {
	//排序
	sort.Ints(piles)
	minh:=len(piles)
	if minh > h{
		return -1
	}
	start:=1
	end:=piles[len(piles) - 1]
	for start<=end{
		mid:=start+(end-start)/2
		if mid==0{
			return -1
		}
		hours:=getHours(piles,mid)
		if hours<=h{
			if mid==1 ||getHours(piles,mid-1)>h {
				return mid
			}
			end =  mid - 1
		} else{
			//说明小了
			start = mid + 1
		}
	}
	return -1
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值