遇到一个面经上的算法题,觉得很有趣,遂答之,这个应该也就是leetcode简单级别
public static void main(String[] args) { int[] cost = {3,4,5,1,2}; int[] gas = {1,2,3,4,5}; System.out.println(byteDance(cost,gas,3)); } public static int byteDance(int[] cost,int[] gas,int num) { int sum = gas[num] - cost[num]; if(sum < 0) return -1; int next = num == gas.length -1 ? 0 : num + 1; while(num != next) { sum = sum + gas[next] - cost[next]; if (sum < 0) return -1; next = next == gas.length -1 ? 0 : next + 1; } return num; }
当然,测试用例不够,我也只是把题目中的数据都改了一遍,因为题目有些歧义,所以我默认工区号是0,1,2,3,4,反正是环形,都差不多