๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[์ธํ๋ฐ ์น์
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;
}
}