์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜7] ๋งˆ๊ตฌ๊ฐ„ ์ •ํ•˜๊ธฐ (Javascript)

์€์ง„ 2021. 6. 28. 00:00

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜7] ๋งˆ๊ตฌ๊ฐ„ ์ •ํ•˜๊ธฐ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-28

1. ์ธ์ ‘ํ•œ ๋ง ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ๋Œ€๊ฐ€ ๋˜๋„๋ก, ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋‘ ๋ง์˜ ์ตœ๋Œ€๊ฑฐ๋ฆฌ

  • 3๋งˆ๋ฆฌ ๋ง์„ ๋ฐฐ์น˜
  • 1, 4, 9๋กœ ๋ฐฐ์น˜ํ•  ๊ฒฝ์šฐ ์ธ์ ‘ํ•œ ๋ง ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ๋Œ€
  • ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋‘ ๋ง์˜ ์ตœ๋Œ€๊ฑฐ๋ฆฌ๋Š” 4-1 = 3

2. ๋‘ ๋ง์˜ ์ตœ๋Œ€๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•ด์•ผ ํ•˜๋ฏ€๋กœ

  • ๋‘ ๋ง ์‚ฌ์ด์˜ ๋ชจ๋“  ์ข…๋ฅ˜์˜ ๊ฑฐ๋ฆฌ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ, ์ด๋ถ„๊ฒ€์ƒ‰
  • left, right๋Š” ๋ณด๋‹ค ๋‹จ์ˆœํ•˜๊ฒŒ ๊ตฌํ˜„
  • ๋‘ ๋ง ์‚ฌ์ด์˜ ์ตœ์†Œ๊ฑฐ๋ฆฌ๋ฅผ mid๋ผ ํ–ˆ์„ ๋•Œ, ๋งˆ๊ตฌ๊ฐ„์— ๋„ฃ์„ ์ˆ˜ ์žˆ๋Š” ๋ง์€ ์ด ๋ช‡๋งˆ๋ฆฌ์ธ์ง€ ํ™•์ธ
let left = Math.min(...arr), right = Math.max(...arr);

while (left <= right) {
  let mid = Math.floor((left + right) / 2);
  let cnt = count(arr, target);

  if (cnt === mid) return mid;
  else if (cnt < mid) right = mid-1; // 2๋งˆ๋ฆฌ๋ฐ–์— ๋ชป๋„ฃ์Œ, ๊ทธ ๋ง์€ ์ตœ์†Œ๊ฑฐ๋ฆฌ๊ฐ€ ์ •๋‹ต๋ณด๋‹ค ํฌ๋‹ค๋Š” ๋ง, ์ตœ์†Œ๊ฑฐ๋ฆฌ๋ฅผ ์ค„์—ฌ์•ผ ํ•จ
  else if (cnt > mid) left = mid+1;
}

3. if (cnt === mid) ์ธ ๊ฒฝ์šฐ ๋ฌด์กฐ๊ฑด return ํ•˜๋ฉด ์•ˆ๋œ๋‹ค.

  • mid-1, mid-2, โ€ฆ ๋„ ๋ฌธ์ œ์กฐ๊ฑด์„ ๋งŒ์กฑํ•  ์ˆ˜ ์žˆ๋‹ค.
if (cnt <= mid) {
  res = mid;
  right = mid-1; 
}
else if (cnt > mid) left = mid+1;

4. count(arr, mid) ๊ตฌํ˜„

  • ๋ง ์‚ฌ์ด์˜ ์ตœ์†Œ๊ฑฐ๋ฆฌ๊ฐ€ mid์ผ ๋•Œ, ๋งˆ๊ตฌ๊ฐ„์— ๋„ฃ์„ ์ˆ˜ ์žˆ๋Š” ๋ง์ด ๋ช‡๋งˆ๋ฆฌ์ธ์ง€ return
  • ์ดˆ๊ธฐ๊ฐ’ cnt = 1, index = arr[0];
  • arr[i]๊ฐ€ index + mid๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด cnt++, index = arr[i]
function count(arr, mid) {
  let cnt = 1, index = arr[0];

  for (let i=1; i<arr.length; i++) {
    if (arr[i] >= index + mid) {
      cnt++;
      index = arr[i];
    }
  }

  return cnt;
}


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-28

function count(arr, mid) {
  let cnt = 1, index = arr[0];

  for (let i=1; i<arr.length; i++) {
    if (arr[i] >= index + mid) {
      cnt++;
      index = arr[i];
    }
  }

  return cnt;
}

function solution(arr, target) {
  let res = 0;
  arr.sort((a, b) => a-b);
  let left = arr[0], right = arr[arr.length-1];
  // ์ •๋ ฌ์ด ํ•„์š”์—†๋‹ค๋ฉด let left = Math.min(...arr), right = Math.max(...arr);

  while (left <= right) {
    let mid = Math.floor((left + right) / 2);
    let cnt = count(arr, target);

    if (cnt <= mid) {
      res = mid;
      right = mid-1; 
    }
    else if (cnt > mid) left = mid+1;
  }

  return res;
}