Skip to content

Commit

Permalink
feat(LeetCode): add solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
plskz committed Apr 4, 2023
1 parent 0281145 commit 7022d28
Show file tree
Hide file tree
Showing 4 changed files with 103 additions and 0 deletions.
23 changes: 23 additions & 0 deletions LeetCode/first-bad-version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* The knows API is defined in the parent class Relation.
* isBadVersion(version: number): boolean {
* ...
* };
*/

var solution = function (isBadVersion: any) {
return function (n: number): number {
let l = 0, r = n;

while (l < r) {
let mid = Math.floor(l + (r - l) / 2);

if (isBadVersion(mid)) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
};
36 changes: 36 additions & 0 deletions LeetCode/optimal-partition-of-string.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Solution 1
function partitionString(s: string): number {
const lastSeen: number[] = new Array(26).fill(-1);

let count: number = 1;
let substrStart: number = 0;

for (let i = 0; i < s.length; i++) {
if (lastSeen[s.charCodeAt(i) - 'a'.charCodeAt(0)] >= substrStart) {
count++;
substrStart = i;
}
lastSeen[s.charCodeAt(i) - 'a'.charCodeAt(0)] = i;
}

return count;
}

// Solution 2
function partitionString2(s: string): number {
let ans: number = 1;
const charSet: Set<string> = new Set();

for (const ch of s) {
if (!charSet.has(ch)) {
charSet.add(ch);
continue;
}

ans++;
charSet.clear();
charSet.add(ch);
}

return ans;
}
39 changes: 39 additions & 0 deletions LeetCode/search-insert-position.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Solution 1
function searchInsert(nums: number[], target: number): number {
let l = 0;
let r = nums.length - 1;

while (l < r) {
let mid = Math.floor(l + (r - l) / 2);

if (nums[mid] === target) return mid;

if (nums[mid] < target) {
l = mid + 1;
} else {
r = mid - 1;
}
}

return nums[l] < target ? l + 1 : l;
}

// Solution 2
function searchInsert2(nums: number[], target: number): number {
let l = 0;
let r = nums.length - 1;

while (l <= r) {
let mid = Math.floor(l + (r - l) / 2);

if (nums[mid] === target) return mid;

if (nums[mid] < target) {
l = mid + 1;
} else {
r = mid - 1;
}
}

return l;
}
5 changes: 5 additions & 0 deletions LeetCode/squares-of-a-sorted-array.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
function sortedSquares(nums: number[]): number[] {
return nums.map((x) => x * x).sort((a, b) => a - b);
}

// TODO: solve follow-up question

0 comments on commit 7022d28

Please sign in to comment.