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 Mar 30, 2023
1 parent ab19887 commit f887ce3
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function strStr(haystack: string, needle: string): number {
return haystack.indexOf(needle);
}
56 changes: 56 additions & 0 deletions LeetCode/longest-continuous-increasing-subsequence.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// https://leetcode.com/problems/longest-continuous-increasing-subsequence/solutions/3359434/javascript-typescript-solution/

function findLengthOfLCIS(nums: number[]): number {
let cur = 1;
let ans = 1;

for (let i = 1; i < nums.length; i++) {
// if (nums[i] > nums[i - 1]) {
// cur += 1
// ans = Math.max(cur, ans)
// } else {
// cur = 1;
// }

// same above. using ternary operator
cur = nums[i] > nums[i - 1] ? cur + 1 : 1;
ans = Math.max(cur, ans);
}

return ans;
}

// cur=1, ans=1

// [1,3,5,4,7] 3 > 1
// 0 1 2 3 4 < i=1

// cur=2, ans=2

// [1,3,5,4,7] 5 > 3
// 0 1 2 3 4 < i=2

// cur=3, ans=3

// [1,3,5,4,7] 4 > 5
// 0 1 2 3 4 < i=3

// cur=1, ans=3

// [1,3,5,4,7] 7 > 4
// 0 1 2 3 4 < i=4

// cur=2, ans=3

// using DP
function findLengthOfLCIS2(nums: number[]): number {
const dp = new Array(nums.length).fill(1);

for (let i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
dp[i] = dp[i - 1] + 1;
}
}

return Math.max(...dp);
}
13 changes: 13 additions & 0 deletions LeetCode/robot-return-to-origin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function judgeCircle(moves: string): boolean {
let x = 0;
let y = 0;

for (let move of moves) {
if (move === 'R') x++;
if (move === 'L') x--;
if (move === 'U') y++;
if (move === 'D') y--;
}

return x === 0 && y === 0;
}

0 comments on commit f887ce3

Please sign in to comment.