Content-Length: 359043 | pFad | http://github.com/GameOfCode64/DSA-JavaScript/commit/fac0849f8cf702758a057e31633d3481eeec101e

6B solve one more Q5 in array · GameOfCode64/DSA-JavaScript@fac0849 · GitHub
Skip to content

Commit fac0849

Browse files
committed
solve one more Q5 in array
1 parent 2f8c9fb commit fac0849

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

Array/day6.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
// Todo: Topic Array
44

5+
// * Q4 Remove Element
56
// * Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
67
// * Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
78
// * Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.

Array/day7.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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

Comments
 (0)








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/GameOfCode64/DSA-JavaScript/commit/fac0849f8cf702758a057e31633d3481eeec101e

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy