Skip to content

Create 0034-find-first-and-last-position-of-element-in-sorted-array.js #2620

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 22, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* Binary Search
* https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
* Time O(log(n)) | Space O(1)
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {

const result = [];

result.push(binarySearch(true));
result.push(binarySearch(false));

function binarySearch(leftBias) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: name booleans that prompt a question

isLeftBias

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a kind reminder that I updated the code as suggested.

let left = 0;
let right = nums.length - 1;
let index = -1;

while(left <= right) {

const mid = Math.floor((left+right)/2);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use bitwise

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


if(target > nums[mid]) {
left = mid+1;
}
if(target < nums[mid]) {
right = mid-1;
}
// this is the meat of the code
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Remove comment and creat descriptive variables or functions

const isTarget = (...);
if (isTarget) { ... }

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done.

if(target === nums[mid]) {
if(leftBias) {
index = mid;
right = mid - 1;
} else {
index = mid;
left = mid + 1;
}
}
}

return index;
}

return result;
};