1276. 不浪费原料的汉堡制作方案

1276. 不浪费原料的汉堡制作方案

解法一: 二分查找

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func numOfBurgers(tomatoSlices int, cheeseSlices int) []int {
if (tomatoSlices & 1) == 1 || (tomatoSlices >> 1) < cheeseSlices || (tomatoSlices >> 2) > cheeseSlices {
return []int{}
}
left := 0
right := tomatoSlices >> 1
for left <= right {
mid := ((right - left) >> 1) + left
target := (mid << 1) + ((cheeseSlices - mid) << 2)
if target == tomatoSlices {
return []int{cheeseSlices - mid, mid}
} else if target > tomatoSlices {
left = mid + 1
} else {
right = mid - 1
}
}
return []int{}
}
作者

wuhunyu

发布于

2023-12-25

更新于

2023-12-25

许可协议