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

[์ธํ”„๋Ÿฐ ์„น์…˜7] ์ด๋ถ„๊ฒ€์ƒ‰ (Javascript)

์€์ง„ 2021. 6. 27. 23:09

์ธํ”„๋Ÿฐ

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

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


โœ๏ธIdea Sketch

2021-06-27

1. ์ •๋ ฌ๋œ ์ƒํƒœ์—์„œ ๋ช‡๋ฒˆ์งธ ์œ„์น˜์ธ์ง€ return

2. sort() ์ •๋ ฌ ์ค‘ target์„ ๋ฐœ๊ฒฌํ•˜๋ฉด return i+1;

๋ฌธ์ œ์ 
sort() ํ•จ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜ ์ค‘ index๋Š” ์—†๋‹ค!
๋”ฐ๋ผ์„œ sort((a, b, i) => {}) ๋ถˆ๊ฐ€

3. ์ด๋ถ„๊ฒ€์ƒ‰์„ ํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ

  • sort() ์ •๋ ฌ ํ›„ arr.indexOf(target)


4. ์ด๋ถ„๊ฒ€์ƒ‰ ๊ตฌํ˜„

  • left, right, mid
  • left = 0, right = arr.length, mid = Math.floor((right+left)/2)
if (arr[mid] === target) return mid+1;
else if (arr[mid] < target) left = mid;
else if (arr[mid] > target) right = mid;


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

2021-06-27 ์ด๋ถ„๊ฒ€์ƒ‰ X

function solution(arr, target) {
    arr.sort((a, b) => a - b);
    return arr.indexOf(target) + 1;
}


2021-06-27 ์ด๋ถ„๊ฒ€์ƒ‰

function solution(arr, target) {
    arr.sort((a, b) => a - b);

    let left = 0, right = arr.length;
    while (true) {
        let mid = Math.floor((right + left) / 2);

        if (arr[mid] === target) return mid+1;
        else if (arr[mid] < target) left = mid;
        else if (arr[mid] > target) right = mid;
    }
}

๋†“์นœ ๊ฒƒ 3๊ฐ€์ง€

  • let left = 0, right = arr.length-1;
  • while(left <= right)
  • left = mid+1, right = mid-1;
function solution(arr, target) {
    arr.sort((a, b) => a - b);

    let left = 0, right = arr.length - 1;
    while (left <= right) {
        let mid = Math.floor((right + left) / 2);

        if (arr[mid] === target) return mid+1;
        else if (arr[mid] < target) left = mid+1;
        else if (arr[mid] > target) right = mid-1;
    }
}