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 查找山峰顶部
力扣https://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 排序中只出现一次的数字
力扣https://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 求平方根
力扣https://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 狒狒吃香蕉
力扣https://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
}