|
| 1 | +// ! DSA in JavaScript day 5 |
| 2 | + |
| 3 | +// Todo: Topic Array |
| 4 | + |
| 5 | +// * Q5, Search Insert Position |
| 6 | +// * Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. |
| 7 | +// * You must write an algorithm with O(log n) runtime complexity |
| 8 | + |
| 9 | +// * Input: nums = [1,3,5,6], target = 5 , Output: 2 |
| 10 | +// * Input: nums = [1,3,5,6], target = 2 , Output: 1 |
| 11 | + |
| 12 | +// * First Try (Pass all Test Case (but Wrong Answer)) |
| 13 | +function searchInsert(nums, target) { |
| 14 | + for (let i = 0; i < nums.length; i++) { |
| 15 | + if (nums[i] >= target) { |
| 16 | + return i; |
| 17 | + } |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +console.log(searchInsert([1, 3, 5, 6], 5)); |
| 22 | + |
| 23 | +// * Write Answer Using Binary Search (I don't Study Yet! 🤡) |
| 24 | +function searchInsert1(nums, target) { |
| 25 | + let left = 0; |
| 26 | + let right = nums.length - 1; |
| 27 | + |
| 28 | + while (left <= right) { |
| 29 | + let mid = Math.floor((left + right) / 2); |
| 30 | + if (nums[mid] === target) { |
| 31 | + return mid; |
| 32 | + } else if (nums[mid] < target) { |
| 33 | + left = mid + 1; |
| 34 | + } else { |
| 35 | + right = mid - 1; |
| 36 | + } |
| 37 | + } |
| 38 | + return left; |
| 39 | +} |
| 40 | + |
| 41 | +console.log(searchInsert1([1, 3, 5, 6], 5)); |
0 commit comments