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 6, 2023
1 parent 0115a35 commit f7c9b39
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
10 changes: 10 additions & 0 deletions LeetCode/merge-sorted-array.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
Do not return anything, modify nums1 in-place instead.
*/
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
nums1.splice(m, nums1.length);
nums1.push(...nums2);
nums1.sort((a, b) => a - b);
}

// TODO: solve it without using built-in function
12 changes: 12 additions & 0 deletions LeetCode/number-of-1-bits.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// https://leetcode.com/problems/number-of-1-bits/solutions/3385115/javascript-typescript-solution-explanation/

function hammingWeight(n: number): number {
let count = 0;
let binaryString = n.toString(2); // convert number to its binary (base 2)

for (const char of binaryString) {
if (char === '1') count++;
}

return count;
}
38 changes: 38 additions & 0 deletions LeetCode/two-sum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Solution 1: using brute force O(n^2)
function twoSum(nums: number[], target: number): number[] {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) return [i, j];
}
}

return [];
}

// Solution 2: sort + two pointers O(nlogn)
function twoSum2(nums: number[], target: number): number[] {
const sortedNums = [...nums].sort((a, b) => a - b);

let l = 0;
let r = sortedNums.length - 1;

while (l < r) {
const sum = sortedNums[l] + sortedNums[r];

if (sum === target) {
const leftIndex = nums.indexOf(sortedNums[l]);
const rightIndex = nums.lastIndexOf(sortedNums[r]);
return [leftIndex, rightIndex];
}

if (sum < target) {
l++;
} else {
r--;
}
}

return [];
}

// TODO: add another approach

0 comments on commit f7c9b39

Please sign in to comment.