๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 881 - Boats to Save People (Medium)

by HandHand 2021. 3. 4.

๋ฌธ์ œ

LeetCode - 881๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ตœ๋Œ€ 2๋ช…์ด ํƒˆ ์ˆ˜ ์žˆ๋Š” ๋ณดํŠธ๋ฅผ ์ด์šฉํ•ด์„œ ๋ชจ๋“  ์‚ฌ๋žŒ๋“ค์„ ์˜ฎ๊ธฐ๋Š” ์ตœ์†Œ ์™•๋ณต ์ด๋™ ํšŸ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๊ทธ๋ฆฌ๋”” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์šฐ์„  ์‚ฌ๋žŒ๋“ค์˜ ๋ชธ๋ฌด๊ฒŒ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•ด์„œ ๋ณดํŠธ์— ์ˆœ์„œ๋Œ€๋กœ ํƒœ์šฐ๋„๋ก ํ•ฉ๋‹ˆ๋‹ค.
์—ฌ๊ธฐ์„œ ์ƒ๊ฐํ•ด๋ณผ ์ ์€ people[head] < limit ์ผ ๋•Œ ๋‚จ์€ ์‚ฌ๋žŒ์€ limit - people[head] ๋ณด๋‹ค ์ ์€ ๋ชธ๋ฌด๊ฒŒ ์ค‘
๊ฐ€์žฅ ํฐ ๋ฌด๊ฒŒ A ๋ฅผ ๊ฐ€์ง€๋Š” ์‚ฌ๋žŒ์„ ์„ ํƒํ•  ๊ฒƒ์ธ์ง€ ํ˜น์€ ๋‚จ์€ ์‚ฌ๋žŒ๋“ค ์ค‘ ๊ฐ€์žฅ ๋ฌด๊ฒŒ๊ฐ€ ์ ๊ฒŒ ๋‚˜๊ฐ€๋Š” ์‚ฌ๋žŒ B ์„ ์„ ํƒํ•  ๊ฒƒ์ธ์ง€ ์ž…๋‹ˆ๋‹ค.

์ด๋•Œ A ๋ฅผ ์„ ํƒํ•˜๋“  B ๋ฅผ ์„ ํƒํ•˜๋“  ์„ ํƒ๋˜์ง€ ์•Š์€ ๋‹ค๋ฅธ ํ•˜๋‚˜๋ฅผ ์œ„ํ•ด ๋ณดํŠธ๊ฐ€ ํ•˜๋‚˜ ํ•„์š”ํ•˜๋‹ค๋Š” ์‚ฌ์‹ค์€ ๋ณ€ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
๋”ฐ๋ผ์„œ ๊ฐ€์žฅ ๋ฌด๊ฒŒ๊ฐ€ ๋งŽ์ด ๋‚˜๊ฐ€๋Š” ์‚ฌ๋žŒ์„ ๊ฐ€๋ฆฌํ‚ค๋Š” ํฌ์ธํ„ฐ head ์™€ ๊ฐ€์žฅ ๋ฌด๊ฒŒ๊ฐ€ ์ ์€ ์‚ฌ๋žŒ์„ ๊ฐ€๋ฆฌํ‚ค๋Š” tail ์„ ์‚ฌ์šฉํ•ด์„œ
๋ชจ๋“  ์‚ฌ๋žŒ์„ ์˜ฎ๊ธฐ๋Š”๋ฐ ํ•„์š”ํ•œ ๋ณดํŠธ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} people
 * @param {number} limit
 * @return {number}
 */
var numRescueBoats = function (people, limit) {
  people.sort((a, b) => b - a);

  let answer = 0,
    head = 0,
    tail = people.length - 1;

  while (head <= tail) {
    if (head < tail && people[head] < limit) {
      if (people[tail] <= limit - people[head]) {
        tail--;
      }
    }

    head++;
    answer++;
  }

  return answer;
};
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€