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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 42885] ๊ตฌ๋ช…๋ณดํŠธ (Javascript)

์€์ง„ 2021. 8. 3. 12:49

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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 42885] ๊ตฌ๋ช…๋ณดํŠธ (Javascript)
ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค


โœ๏ธIdea Sketch

2021-07-12

1. ๋ฌธ์ œ ์ดํ•ด

  • ๊ตฌ๋ช…๋ณดํŠธ๋ฅผ ์ตœ๋Œ€ํ•œ ์ ๊ฒŒ ์‚ฌ์šฉ

2. ๋ชธ๋ฌด๊ฒŒ ์ •๋ ฌ

3. ๋กœ์ง

  • ๋ชธ๋ฌด๊ฒŒ ์ž‘์€ ์‚ฌ๋žŒ๋“ค๋ผ๋ฆฌ ๋ชจ์•„์„œ ๋ณด๋‚ด๊ธฐ
  • ๋ชธ๋ฌด๊ฒŒ ์ž‘์€ ์‚ฌ๋žŒ, ๋ชธ๋ฌด๊ฒŒ ํฐ ์‚ฌ๋žŒ ์ง์ง€์–ด์„œ ๋ณด๋‚ด๊ธฐ

4. ๋ฌธ์ œ์ 

  • ๋ชธ๋ฌด๊ฒŒ ์ž‘์€ ์‚ฌ๋žŒ๋“ค๋ผ๋ฆฌ ๋ชจ์•„์„œ ๋ณด๋‚ด๊ณ  ๋‚˜๋ฉด, limit/2๊ฐ€ ๋„˜๋Š” ์‚ฌ๋žŒ๋“ค์€ ํ•œ๋ช…์”ฉ ๋ณด๋‚ด์•ผ ํ•จ
  • ๋ชธ๋ฌด๊ฒŒ ์ž‘์€ ์‚ฌ๋žŒ, ํฐ ์‚ฌ๋žŒ ์ง์ง€์–ด์„œ ๋ณด๋‚ผ ๊ฒฝ์šฐ [50, 50, 70, 80] ์ž…์ถœ๋ ฅ ์˜ˆ 1๋ฒˆ์„ ๋งŒ์กฑํ•˜์ง€ ์•Š์Œ

5. ๋กœ์ง

  • limit/2๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‘ ๋ถ„๋ฅ˜๋กœ ๋‚˜๋ˆ”
  • limit/2์—์„œ left, right๊ฐ€ ๋‚˜์˜ด -> arr.indexOf(limit/2) ์ด๊ฑฐ๋ฅผ ์“ธ ์ˆ˜๋„ ์—†๊ณ  ๋ง์ด์ง€..?
  • ์ขŒ, ์šฐ์—์„œ left, right
  • sum์ด limit๋ณด๋‹ค ํฌ๋ฉด --> right--, cnt++
  • sum์ด limit์™€ ๊ฐ™์œผ๋ฉด --> left++, right--, cnt++
  • sum์ด limit๋ณด๋‹ค ์ž‘์œผ๋ฉด
    • sum += (left+1) ์ด limit๋ณด๋‹ค ์ž‘์œผ๋ฉด left++, sum += left
    • sum += (left+1) ์ด limit์™€ ๊ฐ™์œผ๋ฉด left++, cnt++
    • sum += (left+1) ์ด limit๋ณด๋‹ค ํฌ๋ฉด left++, right--, cnt++
arr.sort((a, b) => a-b);

let cnt = 0;
let left = 0, right = arr.length-1;
let sum = arr[left] + arr[right];
let flag = false;

while(left <= right) {
  if (sum === limit) {
    cnt++;
    flag = false;
    sum = arr[++left] + arr[--right];
  }
  else if (sum > limit) {
    if (flag === false) {
      cnt++;
      sum = arr[left] + arr[--right];
    }
    else {
      cnt++;
      sum = arr[left] + arr[--right];
    }
  }
  else if (sum < limit) {
    sum += arr[++left];
    flag = true;
  }
}

6. cnt ๋กœ์ง

  • Set()์„ ์‚ฌ์šฉํ•ด myset.delete(left), myset.delete(right)๋ฅผ ํ• ๊นŒ? --> ํšจ์œจ์„ฑ๋ฌธ์ œ ์ƒ๊ธธ๋“ฏ
  • ์ธ๋ฑ์Šค ์ด๋™๋งŒ ํ• ๊นŒ left++ right--


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

2021-07-12 ์ •ํ™•์„ฑ, ํšจ์œจ์„ฑ ํ†ต๊ณผ

function solution(arr, limit) {
  let cnt = 0;

  arr.sort((a, b) => a - b);
  let left = 0, right = arr.length - 1;
  let sum = arr[left] + arr[right];
  let flag = false;  // sum์— left๋ฅผ 2๋ฒˆ ์ด์ƒ ๋”ํ•œ ๊ฒฝ์šฐ true

  while (left <= right) {
    if (left === right) return ++cnt;
    if (sum === limit) {
      cnt++;
      flag = false;
      sum = arr[++left] + arr[--right];
    }
    else if (sum > limit) {
      cnt++;
      flag = false;
      sum = arr[left] + arr[--right];
    }
    else if (sum < limit) {
      flag = true;
      sum += arr[++left];
    }
  }
  return cnt;
}

โœ๏ธ๋ช…๋‹ต

function solution(people, limit) {
    people.sort(function(a, b){return a-b});
    for(var i=0, j=people.length-1; i < j; j--) {
        if( people[i] + people[j] <= limit ) i++;
    }    
    return people.length-i;
}