134. Gas Station

  • 첫번째 index 0λΆ€ν„° μ‹œμž‘ν•΄μ„œ λ§Œμ•½ tank의 기름이 0보닀 μž‘μ•„μ§€λ©΄ λ‹€μŒ μœ„μΉ˜λ₯Ό μƒˆλ‘œμš΄ μ‹œμž‘μ μœΌλ‘œ ν•˜μ—¬ νƒμƒ‰ν•œλ‹€.
  • countλ₯Ό μ‚¬μš©ν•˜μ—¬ λͺ¨λ“  station을 λ°©λ¬Έν–ˆλŠ”μ§€ κΈ°λ‘ν•œλ‹€.
  • start의 λ²”μœ„κ°€ array sizeλ₯Ό λ„˜μ–΄κ°€κ²Œ 되면 μ‹œμž‘μ μ„ μ°Ύμ§€ λͺ»ν•œκ²Œ λ˜λ―€λ‘œ 탐색을 μ’…λ£Œν•œλ‹€.
class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int start = 0; int pos = 0; int tank = 0; int count = 0; while (count < gas.size() and start < gas.size()) { int index = pos % gas.size(); tank += gas[index] - cost[index]; if (tank < 0) { start = ++pos; tank = count = 0; } else { ++pos; ++count; } } return count == gas.size()? start : -1; } };