๐Ÿฅž BE
home

134_Gas Station

๋‹ด๋‹น์ž
์™„๋ฃŒ ์—ฌ๋ถ€
Solved
์š”์•ฝ
๋‚ ์งœ
2024/08/29
ํƒœ๊ทธ
๊ทธ๋ฆฌ๋””
๋‚œ์ด๋„
Medium
์ถœ์ฒ˜
LeetCode

์ฝ”๋“œ

class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int totalGas = 0, totalCost = 0, currentGas = 0; int start = 0; for (int i = 0; i < gas.length; i++) { totalGas += gas[i]; totalCost += cost[i]; currentGas = gas[i] - cost[i]; // ํ˜„์žฌ ์—ฐ๋ฃŒ๊ฐ€ ์Œ์ˆ˜๊ฐ€ ๋˜๋ฉด, ๋‹ค์Œ ์ถœ๋ฐœ์ ์œผ๋กœ ๊ฐฑ์‹  if (currentGas < 0) { start = i + 1; currentGas = 0; } } // ์ „์ฒด ๊ฐ€์Šค๊ฐ€ ์ „์ฒด ๋น„์šฉ๋ณด๋‹ค ๋งŽ์œผ๋ฉด ์ˆœํšŒ๊ฐ€ ๊ฐ€๋Šฅ if (totalGas >= totalCost) { return start; } else { return -1; } } }
Java
๋ณต์‚ฌ

๋ฌธ์ œ ํ•ด๊ฒฐ ์•„์ด๋””์–ด

์ „์ฒด ๊ฐ€์Šค๊ฐ€ ์ „์ฒด ๋น„์šฉ๋ณด๋‹ค ๋งŽ์œผ๋ฉด ๋ฐ˜๋“œ์‹œ ํ•˜๋‚˜์˜ ์ถœ๋ฐœ์ ์ด ์กด์žฌํ•˜๊ณ  ์ˆœํšŒ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค. ์ด๋ฅผ ํ™œ์šฉํ•ด์„œ, ํ˜„์žฌ ์—ฐ๋ฃŒ๊ฐ’์— ๋”ฐ๋ผ ์ถœ๋ฐœ์ ์„ ๊ฐฑ์‹ ํ•ด๊ฐ€๋ฉฐ ๊ทธ๋ฆฌ๋””ํ•˜๊ฒŒ ๋ฌธ์ œ ํ’€์ด๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.