C语言游戏有个玩法会每小时产出相应的资源,人家可以通过累计该资源换取一定奖励,给另一个一为整数数组res,其中res i表示从开始到i小时中累计的资源总量,给定领取奖励所需要的资源总量trget,请计算可以领取该奖励的最早时间,如果无法领奖,返回-1,
时间: 2023-05-24 12:05:18 浏览: 65
思路:利用二分查找找到第一个资源总量大于等于目标奖励的时刻,即为最早时间。
具体实现:
1.初始化左边界l为0,右边界r为res数组长度-1。
2.进入循环,当左边界小于等于右边界时执行,每次取中间位置mid,判断res[mid]是否大于等于目标奖励,若是则更新右边界r为mid-1,若不是则更新左边界l为mid+1。
3.循环结束后,判断左边界是否大于等于res数组长度或该位置的资源总量小于目标奖励,若是则说明无法领奖,返回-1,否则返回左边界即为最早时间。
代码如下:
```c
int earliest_time(int* res, int size, int target) {
int l = 0, r = size - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (res[mid] >= target)
r = mid - 1;
else
l = mid + 1;
}
return l >= size || res[l] < target ? -1 : l;
}
```
相关问题
C语言游戏有个玩法会每小时产出相应的资源,可以通过累计该资源换取一定奖励,给另一个一为整数数组res,其中res i表示从开始到i小时中累计的资源总量,给定领取奖励所需要的资源总量trget,请计算可以领取该奖励的最早时间,如果无法领奖,返回-1,
假设当前时间为t,那么从开始到t小时中累计的资源总量res[t]可以通过计算res[t] - res[t-1]得到。因此可以使用一个循环来依次计算每个时间点的累计资源总量,直到该总量大于等于目标值target为止。如果循环结束时仍未找到满足条件的时间点,说明无法领取奖励,返回-1。
代码如下:
```c
int get_reward_time(int* res, int n, int target) {
int total = 0; // 累计资源总量
int t = 0; // 当前时间点
while (t < n && total < target) {
total += (t == 0) ? res[t] : res[t] - res[t-1];
t++;
}
if (total < target) {
return -1; // 无法领取奖励
} else {
return t; // 返回最早时间点
}
}
```
该函数的时间复杂度为O(n),空间复杂度为O(1)。
C语言可以在一个函数中定义另一个函数吗
在C语言中,不能在一个函数中定义另一个函数。C语言的函数是独立的代码单元,每个函数都是在程序的顶层作用域中定义的,不能在其他函数中定义。
如果需要在一个函数中使用另一个函数,可以将需要使用的函数放在调用函数之前,或者将需要使用的函数声明为全局函数,然后在调用函数中进行调用。
以下是一个在C语言中定义和调用全局函数的示例代码:
```
#include <stdio.h>
// 声明全局函数
void func2();
void func1() {
printf("This is function 1.\n");
// 调用全局函数
func2();
}
void func2() {
printf("This is function 2.\n");
}
int main() {
func1();
return 0;
}
```
输出结果为:
```
This is function 1.
This is function 2.
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)