LeetCode-134.加油站
一、C实现
1. 参考:https://zhuanlan.zhihu.com/p/299991342
2. C实现
#include <stdio.h> #include <stdlib.h> #define ARRAY_SIZE(arr) (sizeof(arr)/sizeof(arr[0])) int max_val(int x, int y) { return x > y ? x : y; } int min_val(int x, int y) { return x > y ? y : x; } int canCompleteCircuit(int *gas, int gsz, int *cost) { int i, j, remain, ret = -1; for (i = 0; i < gsz; i++) { remain = gas[i]; j = i; while(remain >= cost[j]) { remain += gas[(j+1)%gsz] - cost[j]; j = (j + 1) % gsz; if (j == i) { printf("start at %d ok!\n", i); ret = 0; break; } } } return ret; } int main() { int ret; int gas[] = {1,2,3,4,5}; int cost[] = {3,4,5,1,2}; ret = canCompleteCircuit(gas, ARRAY_SIZE(gas), cost); printf("ret=%d\n", ret); return 0; } /* start at 3 ok! ret=0 */
posted on 2025-02-16 16:35 Hello-World3 阅读(11) 评论(0) 收藏 举报