diff --git a/Problems/.DS_Store b/Problems/.DS_Store index 5f39ce6..107a95d 100644 Binary files a/Problems/.DS_Store and b/Problems/.DS_Store differ diff --git a/Problems/01-Same-Tree/Same_tree2.py b/Problems/01-Same-Tree/Same_tree2.py new file mode 100644 index 0000000..30cf25d --- /dev/null +++ b/Problems/01-Same-Tree/Same_tree2.py @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def isSameTree(self, p, q) : + """ + :type p: TreeNode + :type q: TreeNode + :rtype: bool + """ + if(not p and not q): return True + elif p and q and p.val== q.val: + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) + else: return False diff --git a/Problems/02-Symmetric-Tree/symetric_tree.py b/Problems/02-Symmetric-Tree/symetric_tree.py new file mode 100644 index 0000000..357d578 --- /dev/null +++ b/Problems/02-Symmetric-Tree/symetric_tree.py @@ -0,0 +1,18 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def isSymmetric(self, root): + """ + :type root: TreeNode + :rtype: bool + """ + def compare(n1,n2): + if not n1 and not n2 : return True + elif not n1 or not n2 : return False + elif n1.val != n2.val : return False + return compare(n1.left,n2.right) and compare(n1.right,n2.left) + return compare(root,root) \ No newline at end of file diff --git a/Problems/03-Balanced-Binary-Tree/balanced_binary_tree2.py b/Problems/03-Balanced-Binary-Tree/balanced_binary_tree2.py new file mode 100644 index 0000000..57e5b35 --- /dev/null +++ b/Problems/03-Balanced-Binary-Tree/balanced_binary_tree2.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def isBalanced(self, root): + """ + :type root: TreeNode + :rtype: bool + """ + n = self.diff(root) + if n == -1: return False + else: return True + + def diff(self,root): + if root == None: return 0 + hautL = self.diff(root.left) + hautR = self.diff(root.right) + if hautL >= 0 and hautR >= 0 and abs(hautL-hautR) <= 1: return max(hautR,hautL)+1 + else: return -1 \ No newline at end of file diff --git a/Problems/04-Path-Sum/Path-Sum.cpp b/Problems/04-Path-Sum/Path-Sum.cpp new file mode 100644 index 0000000..515943d --- /dev/null +++ b/Problems/04-Path-Sum/Path-Sum.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool hasPathSum(TreeNode* root, int targetSum) { + if (root == nullptr) return false; + if (root->left == nullptr and root->right == nullptr) return root->val == targetSum; + return hasPathSum(root->left, targetSum-root->val) or hasPathSum(root->right, targetSum-root->val); + } +}; \ No newline at end of file diff --git a/Problems/04-Path-Sum/Path-Sum.ts b/Problems/04-Path-Sum/Path-Sum.ts new file mode 100644 index 0000000..df589f4 --- /dev/null +++ b/Problems/04-Path-Sum/Path-Sum.ts @@ -0,0 +1,52 @@ + /** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + + /** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + + function hasPathSum(root: TreeNode | null, targetSum: number): boolean { + if(!root) return false; + let res: boolean = false; + let sum: number = 0; + //不是简洁的写法,但是回溯思路比较清晰 + function dfs(node: TreeNode | null) { + if(!node) return; + if(node.left === null && node.right === null){ + if(sum + node.val === targetSum){ + res = true; + return + } + } + sum += node.val; + dfs(node.left); + sum -= node.val; + + sum += node.val; + dfs(node.right); + sum -= node.val; + } + dfs(root); + return res; +} \ No newline at end of file diff --git a/Problems/04-Path-Sum/path_sum.py b/Problems/04-Path-Sum/path_sum.py new file mode 100644 index 0000000..072f988 --- /dev/null +++ b/Problems/04-Path-Sum/path_sum.py @@ -0,0 +1,18 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def hasPathSum(self, root, targetSum): + """ + :type root: TreeNode + :type targetSum: int + :rtype: bool + """ + if root == None : return False + newTarget = targetSum-root.val + if root.left == None and root.right == None and newTarget == 0: + return True + return self.hasPathSum(root.left,newTarget) or self.hasPathSum(root.right,newTarget) \ No newline at end of file diff --git a/Problems/05-Minimum-Absolute-Difference-in-BST/530-Minimum-Absolute-Difference-in-BST.ts b/Problems/05-Minimum-Absolute-Difference-in-BST/530-Minimum-Absolute-Difference-in-BST.ts new file mode 100644 index 0000000..45f4280 --- /dev/null +++ b/Problems/05-Minimum-Absolute-Difference-in-BST/530-Minimum-Absolute-Difference-in-BST.ts @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function getMinimumDifference(root: TreeNode | null): number { + let res: number = Infinity; + let preNodeVal: number; + //二叉搜索树采用中序遍历,其实就是一个有序数组。 + function recur(node: TreeNode | null) { + if(node === null) return + recur(node.left); + if(preNodeVal!==null && Math.abs(preNodeVal-node.val) < res){ + res = Math.abs(preNodeVal-node.val); + } + preNodeVal = node.val; + recur(node.right); + } + recur(root); + return res; +}; \ No newline at end of file diff --git a/Problems/05-Minimum-Absolute-Difference-in-BST/Minimum-Absolute-Difference-in-BST.cpp b/Problems/05-Minimum-Absolute-Difference-in-BST/Minimum-Absolute-Difference-in-BST.cpp new file mode 100644 index 0000000..548d1c4 --- /dev/null +++ b/Problems/05-Minimum-Absolute-Difference-in-BST/Minimum-Absolute-Difference-in-BST.cpp @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* prev = nullptr; + void dfs(TreeNode* root, int& minDifference) + { + if (root->left) + { + dfs(root->left, minDifference); + } + + if (prev != nullptr) + { + minDifference = min(minDifference, abs(root->val - prev->val)); + } + + prev = root; + + if (root->right) + { + dfs(root->right, minDifference); + } + } + + int getMinimumDifference(TreeNode* root) { + int minDifference = INT_MAX; + dfs(root, minDifference); + return minDifference; + } +}; \ No newline at end of file diff --git a/Problems/05-Minimum-Absolute-Difference-in-BST/Q530.cpp b/Problems/05-Minimum-Absolute-Difference-in-BST/Q530.cpp new file mode 100644 index 0000000..0c21b5a --- /dev/null +++ b/Problems/05-Minimum-Absolute-Difference-in-BST/Q530.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int getMinimumDifference(TreeNode* root) { + vector sorted; + inorder(root,sorted); + int min_diff = sorted.back(); // the largest one + for(int i=1; i& sorted){ // Time complexity : O(n) + if(!root) return; + inorder(root->left,sorted); + sorted.push_back(root->val); + inorder(root->right,sorted); + } +}; \ No newline at end of file diff --git a/Problems/05-Minimum-Absolute-Difference-in-BST/mini_abs_diff.py b/Problems/05-Minimum-Absolute-Difference-in-BST/mini_abs_diff.py new file mode 100644 index 0000000..1f2d28f --- /dev/null +++ b/Problems/05-Minimum-Absolute-Difference-in-BST/mini_abs_diff.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def getMinimumDifference(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def inorder(root): + if not root : return [] + return inorder(root.left)+[root.val]+inorder(root.right) + + mini = float("inf") + inord = inorder(root) + for i in range(1,len(inord)): + mini = min(mini,inord[i]-inord[i-1]) + return mini + \ No newline at end of file diff --git a/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235-LCA-BST.ts b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235-LCA-BST.ts new file mode 100644 index 0000000..9260745 --- /dev/null +++ b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/235-LCA-BST.ts @@ -0,0 +1,26 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null { + while (root) { + if (root.val < p.val && root.val < q.val) { + root = root.right; + } + else if (root.val > p.val && root.val > q.val) { + root = root.left; + } else { + return root; + } + } +} \ No newline at end of file diff --git a/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cpp b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cpp new file mode 100644 index 0000000..458d34e --- /dev/null +++ b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cpp @@ -0,0 +1,26 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root == NULL) return NULL; + if (root->val == p->val || root->val == q->val) + { + return root; + } + + auto LCA_left = lowestCommonAncestor(root->left, p, q); + auto LCA_right = lowestCommonAncestor(root->right, p, q); + + if (LCA_left && LCA_right) return root; + return (LCA_left)?(LCA_left):(LCA_right); + } +}; \ No newline at end of file diff --git a/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Q235-Lowest-Common-LCA.py b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Q235-Lowest-Common-LCA.py new file mode 100644 index 0000000..a41a8d4 --- /dev/null +++ b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/Q235-Lowest-Common-LCA.py @@ -0,0 +1,11 @@ +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + cur = root + + while cur: + if p.val > cur.val and q.val > cur.val: + cur = cur.right + elif p.val < cur.val and q.val < cur.val: + cur = cur.left + else: + return cur \ No newline at end of file diff --git a/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/lowest_common_ancestor.py b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/lowest_common_ancestor.py new file mode 100644 index 0000000..87c5f0f --- /dev/null +++ b/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree/lowest_common_ancestor.py @@ -0,0 +1,18 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def lowestCommonAncestor(self, root, p, q): + """ + :type root: TreeNode + :type p: TreeNode + :type q: TreeNode + :rtype: TreeNode + """ + if max(p.val,q.val)root.val: return self.lowestCommonAncestor(root.right,p,q) + return root \ No newline at end of file diff --git a/Problems/07-All-Elements-in-Two-Binary-Search-Trees/1305-All-Elements-BST.ts b/Problems/07-All-Elements-in-Two-Binary-Search-Trees/1305-All-Elements-BST.ts new file mode 100644 index 0000000..0170cbc --- /dev/null +++ b/Problems/07-All-Elements-in-Two-Binary-Search-Trees/1305-All-Elements-BST.ts @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function getAllElements(root1: TreeNode | null, root2: TreeNode | null): number[] { + function getElements(node: TreeNode | null): number[] { + let res: number[] = []; + let queue: TreeNode[] = []; + while(node || queue.length) { + if(node){ + queue.push(node); + node = node.left; + continue; + } + node = queue.pop(); + res.push(node.val); + node = node.right; + } + return res; + } + let res :number[] = []; + let arr1 = getElements(root1); + let ptr1 = arr1.length-1; + let arr2 = getElements(root2); + let ptr2 = arr2.length-1; + let ptr = arr1.length + arr2.length - 1; + while(ptr >= 0){ + if(ptr2<0 || arr1[ptr1] > arr2[ptr2]) { + res[ptr--] = arr1[ptr1--]; + } else { + res[ptr--] = arr2[ptr2--]; + } + } + return res; +}; \ No newline at end of file diff --git a/Problems/07-All-Elements-in-Two-Binary-Search-Trees/All-Elements-in-Two-Binary-Search-Trees.cpp b/Problems/07-All-Elements-in-Two-Binary-Search-Trees/All-Elements-in-Two-Binary-Search-Trees.cpp new file mode 100644 index 0000000..f50c540 --- /dev/null +++ b/Problems/07-All-Elements-in-Two-Binary-Search-Trees/All-Elements-in-Two-Binary-Search-Trees.cpp @@ -0,0 +1,49 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector getAllElements(TreeNode* root1, TreeNode* root2) { + vector ans; + stack s1, s2; + + while (root1 || root2 || !s1.empty() || !s2.empty()) + { + while (root1) + { + s1.push(root1); + root1 = root1->left; + } + + while (root2) + { + s2.push(root2); + root2 = root2->left; + } + + if(s2.empty() || (!s1.empty() && s1.top()->val <= s2.top()->val)) + { + root1 = s1.top(); + s1.pop(); + ans.push_back(root1->val); + root1 = root1->right; + } + else + { + root2 = s2.top(); + s2.pop(); + ans.push_back(root2->val); + root2 = root2->right; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/07-All-Elements-in-Two-Binary-Search-Trees/All_elements.py b/Problems/07-All-Elements-in-Two-Binary-Search-Trees/All_elements.py new file mode 100644 index 0000000..85d973b --- /dev/null +++ b/Problems/07-All-Elements-in-Two-Binary-Search-Trees/All_elements.py @@ -0,0 +1,26 @@ +class Solution: + def getAllElements(self, root1, root2) : + def inorder(node, res): + if node: + inorder(node.left, res) + res.append(node.val) + inorder(node.right, res) + res,inor1,inor2 = [],[],[] + inorder(root1,inor1) + inorder(root2,inor2) + l1, r1 = 0, len(inor1) + l2, r2 = 0, len(inor2) + while True: + if l1 == r1: + res.extend(inor2[l2:]) + break + if l2 == r2: + res.extend(inor1[l1:]) + break + if inor1[l1] < inor2[l2]: + res.append(inor1[l1]) + l1 += 1 + else: + res.append(inor2[l2]) + l2 += 1 + return res \ No newline at end of file diff --git a/Problems/08-Search-Insert-Position/Search-Insert-Position.cpp b/Problems/08-Search-Insert-Position/Search-Insert-Position.cpp new file mode 100644 index 0000000..a6777f6 --- /dev/null +++ b/Problems/08-Search-Insert-Position/Search-Insert-Position.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int searchInsert(vector& nums, int target) { + int left = 0; + int right = nums.size()-1; + while (left <= right) + { + int mid = (right - left) / 2 + left; + if (nums[mid] == target) return mid; + if (nums[mid] < target) left = mid + 1; + else right = mid - 1; + } + + if (right >= 0 && nums[right] > target) return right; + else return right + 1; + } +}; \ No newline at end of file diff --git a/Problems/08-Search-Insert-Position/Search-Insert-Position.py b/Problems/08-Search-Insert-Position/Search-Insert-Position.py new file mode 100644 index 0000000..c7a3275 --- /dev/null +++ b/Problems/08-Search-Insert-Position/Search-Insert-Position.py @@ -0,0 +1,21 @@ +class Solution(object): + def searchInsert(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + l = len(nums) + i = 0 + j = l-1 + res = l + while (i<=j): + mid = (i+j)/2 + if target == nums[mid]: + res = mid + break + elif target < nums[mid]: + res = mid + j = mid -1 + else: i = mid+1 + return res diff --git a/Problems/08-Search-Insert-Position/Search-Insert-Position.ts b/Problems/08-Search-Insert-Position/Search-Insert-Position.ts new file mode 100644 index 0000000..d07d78c --- /dev/null +++ b/Problems/08-Search-Insert-Position/Search-Insert-Position.ts @@ -0,0 +1,14 @@ +function searchInsert(nums: number[], target: number): number { + + let left: number = 0; + let right: number = nums.length; + let mid: number + while (left < right) { + mid = left + Math.floor((right - left) / 2); + if (nums[mid] >= target) right = mid; + else left = mid + 1; + + } + return left; + +}; \ No newline at end of file diff --git a/Problems/09-Longest-Subsequence-With-Limited-Sum/2389.ts b/Problems/09-Longest-Subsequence-With-Limited-Sum/2389.ts new file mode 100644 index 0000000..3804168 --- /dev/null +++ b/Problems/09-Longest-Subsequence-With-Limited-Sum/2389.ts @@ -0,0 +1,26 @@ +function answerQueries(nums: number[], queries: number[]): number[] { + nums = nums.sort((a, b) => a - b); + let prefix: number[] = [nums[0]]; + let res: number[] = []; + for (let i = 1; i < nums.length; i++) { + prefix.push(prefix[i - 1] + nums[i]); + } + + for (let target of queries) { + let left: number = 0; + let right: number = prefix.length; + let mid: number; + while (left < right) { + mid = left + Math.floor((right - left) / 2); + if (prefix[mid] > target) right = mid; + else if (prefix[mid] === target) { + left = mid + 1; + break; + } + else left = mid + 1; + } + + res.push(left); + } + return res; +}; \ No newline at end of file diff --git a/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest-Subsequence-With-Limited-Sum.cpp b/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest-Subsequence-With-Limited-Sum.cpp new file mode 100644 index 0000000..9c1d67f --- /dev/null +++ b/Problems/09-Longest-Subsequence-With-Limited-Sum/Longest-Subsequence-With-Limited-Sum.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + vector answerQueries(vector& nums, vector& queries) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + vector prefixSum(n+1, 0); + for (int i = 1; i <= n; i++) prefixSum[i] = prefixSum[i-1] + nums[i-1]; + + int m = queries.size(); + vector ans(m, 0); + + for (int i = 0; i < m; i++) + { + int left = 1, right = n; + ans[i] = 0; + while (left <= right) + { + int mid = (right - left) / 2 + left; + if (prefixSum[mid] <= queries[i]) + { + ans[i] = mid; + left = mid + 1; + } + else + { + right = mid - 1; + } + } + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/1385.ts b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/1385.ts new file mode 100644 index 0000000..b25837e --- /dev/null +++ b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/1385.ts @@ -0,0 +1,27 @@ +function findTheDistanceValue(arr1: number[], arr2: number[], d: number): number { + + function isValid(arr: number[], target: number, d: number): boolean { + let left = 0; + let right = arr.length-1; + while(left <= right) { + let mid = left + Math.floor((right-left/2)); + if(Math.abs(target-arr[mid]) <= d) { + return false; + } else if(arr[mid] > target) { + right = mid - 1 ; + } else { + left = mid + 1; + } + } + return true; + } + arr2= arr2.sort((a,b)=>a-b); + let res = 0; + + for(let i of arr1) { + if( isValid(arr2, i, d)){ + res++; + } + } + return res; +}; \ No newline at end of file diff --git a/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find-the-Distance-Value-Between-Two-Arrays.cpp b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find-the-Distance-Value-Between-Two-Arrays.cpp new file mode 100644 index 0000000..0b0a1e4 --- /dev/null +++ b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find-the-Distance-Value-Between-Two-Arrays.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int findTheDistanceValue(vector& arr1, vector& arr2, int d) { + int m = arr2.size(); + int ans = 0; + sort(arr2.begin(), arr2.end()); + for (auto x: arr1) + { + int left = 0, right = m-1; + int index = m-1; + while (left <= right) + { + int mid = (right - left) / 2 + left; + if (arr2[mid] == x) + { + index = mid; + break; + } + else if (arr2[mid] < x) + { + left = mid + 1; + } + else // (arr2[mid] > x) + { + index = mid; + right = mid - 1; + } + } + + if (abs(arr2[index]-x) > d && (index - 1 < 0 || abs(arr2[index-1] -x) > d)) + { + ans += 1; + } + + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distane_value.py b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distane_value.py new file mode 100644 index 0000000..aeec29e --- /dev/null +++ b/Problems/10-Find-the-Distance-Value-Between-Two-Arrays/Find_the_Distane_value.py @@ -0,0 +1,21 @@ +import bisect + +class Solution: + def findTheDistanceValue1(self, arr1, arr2, d): + """ + :type arr1: List[int] + :type arr2: List[int] + :type d: int + :rtype: int + """ + return sum(all(abs(x - y) > d for y in arr2) for x in arr1) + + + def findTheDistanceValue(self, arr1, arr2, d): + arr2.sort() + res = 0 + for n in arr1: + i = bisect.bisect_left(arr2, n) + if (i >= len(arr2) or arr2[i]-n > d) and (i == 0 or n - arr2[i-1] > d): + res += 1 + return res diff --git a/Problems/11-Guess-Number-Higher-or-Lower/374.ts b/Problems/11-Guess-Number-Higher-or-Lower/374.ts new file mode 100644 index 0000000..9a5207b --- /dev/null +++ b/Problems/11-Guess-Number-Higher-or-Lower/374.ts @@ -0,0 +1,21 @@ +/** + * Forward declaration of guess API. + * @param {number} num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * var guess = function(num) {} + */ + + +function guessNumber(n: number): number { + let right = n + 1; + let left = 0; + while (left < right) { + let mid = Math.floor((left + right) / 2); + if (guess(mid) === 0) return mid; + else if (guess(mid) === -1) right = mid; + else if (guess(mid) === 1) left = mid + 1; + } + +}; \ No newline at end of file diff --git a/Problems/11-Guess-Number-Higher-or-Lower/Guess-Number-Higher-or-Lower.cpp b/Problems/11-Guess-Number-Higher-or-Lower/Guess-Number-Higher-or-Lower.cpp new file mode 100644 index 0000000..bc8881a --- /dev/null +++ b/Problems/11-Guess-Number-Higher-or-Lower/Guess-Number-Higher-or-Lower.cpp @@ -0,0 +1,31 @@ +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * int guess(int num); + */ + +class Solution { +public: + int guessNumber(int n) { + if (n == 1) return 1; + int left = 1, right = n; + while (left <= right) + { + int mid = (right - left) / 2 + left; + int res = guess(mid); + if (res == 0) return mid; + if (res == 1) + { + left = mid + 1; + } + else + { + right = mid - 1; + } + } + return left; + } +}; \ No newline at end of file diff --git a/Problems/11-Guess-Number-Higher-or-Lower/Guess_Number_Higher_or_Lower.py b/Problems/11-Guess-Number-Higher-or-Lower/Guess_Number_Higher_or_Lower.py new file mode 100644 index 0000000..9b4e62a --- /dev/null +++ b/Problems/11-Guess-Number-Higher-or-Lower/Guess_Number_Higher_or_Lower.py @@ -0,0 +1,25 @@ +# The guess API is already defined for you. +# @param num, your guess +# @return -1 if num is higher than the picked number +# 1 if num is lower than the picked number +# otherwise return 0 +# def guess(num): + +class Solution(object): + def guessNumber(self, n): + """ + :type n: int + :rtype: int + """ + min, max = 1, n + while min < max: + mid = (min + max) // 2 + res = guess(mid) + if res == 0: + return mid + elif res < 0: + max = mid + else: + min = mid + 1 + + return min \ No newline at end of file diff --git a/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/34.ts b/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/34.ts new file mode 100644 index 0000000..70e22c4 --- /dev/null +++ b/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/34.ts @@ -0,0 +1,33 @@ +function searchRange(nums: number[], target: number): number[] { + + const max = binarySearch(nums, target, true); + + if (max !== undefined) { + const min = binarySearch(nums, target, false); + return [min!, max]; + } + return [-1, -1]; + + function binarySearch(nums: number[], target: number, flag: boolean): number | undefined { + let position: number | undefined; + let left = 0; + let right = nums.length - 1; + while (left <= right) { + let mid = Math.floor((left + right) / 2); + if (nums[mid] > target) { + right = mid - 1; + } else if (nums[mid] < target) { + left = mid + 1; + } else { + position = mid; + if (flag) { + left = left + 1; + } else { + right = right - 1; + } + } + } + return position; + } + +}; \ No newline at end of file diff --git a/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find-First-and-Last-Position-of-Element-in-Sorted-Array.cpp b/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find-First-and-Last-Position-of-Element-in-Sorted-Array.cpp new file mode 100644 index 0000000..30942a6 --- /dev/null +++ b/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find-First-and-Last-Position-of-Element-in-Sorted-Array.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + vector searchRange(vector& nums, int target) { + int n = nums.size(); + int left = 0, right = n-1; + int first = -1; + while (left <= right) + { + int mid = (right - left ) / 2 + left; + if (nums[mid] == target) + { + first = mid; + right = mid - 1; + } + else if (nums[mid] < target) + { + left = mid + 1; + } + else + { + right = mid - 1; + } + } + + if (first == -1) return {-1, -1}; + + int last = -1; + left = 0, right = n-1; + while (left <= right) + { + int mid = (right - left ) / 2 + left; + if (nums[mid] == target) + { + last = mid; + left = mid + 1; + } + else if (nums[mid] < target) + { + left = mid + 1; + } + else + { + right = mid - 1; + } + } + return {first, last}; + } +}; \ No newline at end of file diff --git a/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find_First_and_Last_Position.py b/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find_First_and_Last_Position.py new file mode 100644 index 0000000..ed5d14a --- /dev/null +++ b/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array/Find_First_and_Last_Position.py @@ -0,0 +1,27 @@ +class Solution(object): + def searchRange(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + left = 0 + right = len(nums)-1 + def binarySearch(nums,target,left,right): + while (left <= right): + mid = left + (right-left) / 2 + if(target > nums[mid]): + left = mid + 1 + elif(target < nums[mid]): + right = mid -1 + else: + return mid + return -1 + index = binarySearch(nums,target,left,right) + if index == -1: return [-1,-1] + index2 = index + while index -1 >=0 and nums[index - 1] == target: index -=1 + while index2+1 < len(nums) and nums[index2 + 1] == target: index2 +=1 + return[index,index2] + + \ No newline at end of file diff --git a/Problems/13-Max-Consecutive-Ones-III/485.ts b/Problems/13-Max-Consecutive-Ones-III/485.ts new file mode 100644 index 0000000..6f3c2a6 --- /dev/null +++ b/Problems/13-Max-Consecutive-Ones-III/485.ts @@ -0,0 +1,18 @@ +function findMaxConsecutiveOnes(nums: number[]): number { + let slow: number = 0, fast: number = 0; + let res: number = 0; + while (fast < nums.length) { + if (nums[slow] !== 1 && nums[fast] !== 1) { + slow++; + fast++; + } + else if (nums[slow] === 1 && nums[fast] === 1) { + fast++; + } + else if (nums[fast] !== 1) { + slow = fast; + } + res = res > (fast - slow) ? res : (fast - slow); + } + return res; +}; \ No newline at end of file diff --git a/Problems/13-Max-Consecutive-Ones-III/Max-Consecutive-Ones-III.cpp b/Problems/13-Max-Consecutive-Ones-III/Max-Consecutive-Ones-III.cpp new file mode 100644 index 0000000..9d6f25d --- /dev/null +++ b/Problems/13-Max-Consecutive-Ones-III/Max-Consecutive-Ones-III.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int longestOnes(vector& nums, int k) { + int n = nums.size(); + vector prefixSum(n+1, 0); + for (int i = 1; i <= n; i++) prefixSum[i] = prefixSum[i-1] + nums[i-1]; + + int res = 0; + for (int i = 1; i <= n; i++) + { + int left = i; + int right = n; + + int ans = 0; + while (left <= right) + { + int mid = (right-left)/2+left; + int num0 = (mid-i+1)-prefixSum[mid] + prefixSum[i-1]; // in [i..mid] + if (num0 <= k) {ans = mid; left = mid + 1;} + else {right = mid-1;} + } + + res = max(res, ans - i + 1); + } + + return res; + + } +}; \ No newline at end of file diff --git a/Problems/13-Max-Consecutive-Ones-III/Max_consecutive_ones_III.py b/Problems/13-Max-Consecutive-Ones-III/Max_consecutive_ones_III.py new file mode 100644 index 0000000..63a5927 --- /dev/null +++ b/Problems/13-Max-Consecutive-Ones-III/Max_consecutive_ones_III.py @@ -0,0 +1,19 @@ +class Solution(object): + def longestOnes(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + left ,right = 0,0 + res = 0 + while(right tail) left = mid + 1; + else if (target < head) right = mid - 1; + else if (target <= tail && target >= head) return mid; + } + return -1; + } + + if (searchMx(matrix, target) === -1) return false; + const arr = matrix[searchMx(matrix, target)]; + let left = 0; + let right = arr.length - 1; + while (left <= right) { + let mid = Math.floor((left + right) / 2); + if (arr[mid] > target) right = mid - 1; + else if (arr[mid] < target) left = mid + 1; + else return true; + } + return false; +}; \ No newline at end of file diff --git a/Problems/14-Search-a-2D-Matrix/Search-a-2D-Matrix.cpp b/Problems/14-Search-a-2D-Matrix/Search-a-2D-Matrix.cpp new file mode 100644 index 0000000..f752b70 --- /dev/null +++ b/Problems/14-Search-a-2D-Matrix/Search-a-2D-Matrix.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int getValue(vector>& matrix, int mid) + { + int n = matrix.size(); + int m = matrix[0].size(); + int i = mid / m; + int j = mid % m; + return matrix[i][j]; + } + + bool searchMatrix(vector>& matrix, int target) { + int n = matrix.size(); + int m = matrix[0].size(); + int left = 0, right = n * m-1; + while (left <= right) + { + int mid = (right - left)/2+left; + int value = getValue(matrix, mid); + if (target == value) return true; + if (target < value) right = mid-1; + else left = mid + 1; + } + return false; + } +}; \ No newline at end of file diff --git a/Problems/14-Search-a-2D-Matrix/search_a_2D_Matrix.py b/Problems/14-Search-a-2D-Matrix/search_a_2D_Matrix.py new file mode 100644 index 0000000..998052f --- /dev/null +++ b/Problems/14-Search-a-2D-Matrix/search_a_2D_Matrix.py @@ -0,0 +1,15 @@ +class Solution(object): + def searchMatrix(self, matrix, target): + """ + :type matrix: List[List[int]] + :type target: int + :rtype: bool + """ + k = 0 + + for i in range(len(matrix)): + if(target == matrix[i][0]): return True + if(target> matrix[i][0]): k = i + for j in range(1,len(matrix[k])): + if(target == matrix[k][j]): return True + return False \ No newline at end of file diff --git a/Problems/15-Maximum-Tastiness-of-Candy-Basket/2517.ts b/Problems/15-Maximum-Tastiness-of-Candy-Basket/2517.ts new file mode 100644 index 0000000..5684382 --- /dev/null +++ b/Problems/15-Maximum-Tastiness-of-Candy-Basket/2517.ts @@ -0,0 +1,35 @@ +function maximumTastiness(price: number[], k: number): number { + + let n = price.length; + price = price.sort((a,b)=> a-b); + let left = 0, right = price[n-1] - price[0] , ans = 0; + + while(left <= right){ + let mid = Math.floor(left+(right-left)/2); + if(possible(mid)){ + ans = mid; + left = mid+1; + }else{ + right = mid-1; + } + } + + function possible(diff){ + let count = 1; + let curr = 0; + + for(let i=1; i= diff){ + curr = i; + count++; + } + } + + if(count >= k) return true + else return false; + + } + + return ans; + +}; \ No newline at end of file diff --git a/Problems/15-Maximum-Tastiness-of-Candy-Basket/Max_Tastiness_of_Candy.py b/Problems/15-Maximum-Tastiness-of-Candy-Basket/Max_Tastiness_of_Candy.py new file mode 100644 index 0000000..9ee5932 --- /dev/null +++ b/Problems/15-Maximum-Tastiness-of-Candy-Basket/Max_Tastiness_of_Candy.py @@ -0,0 +1,23 @@ +class Solution(object): + def maximumTastiness(self, price, k): + """ + :type price: List[int] + :type k: int + :rtype: int + """ + price.sort() + def check(d): + cnt, x0 = 1, price[0] + for x in price: + if x - x0 >= d: + cnt += 1 + x0 = x + return cnt >= k + + left = 0 + right = price[-1]-price[0] + while(left < right): + mid = (left+right+1)//2 + if check(mid): left = mid + else: right = mid-1 + return left diff --git a/Problems/15-Maximum-Tastiness-of-Candy-Basket/Maximum-Tastiness-of-Candy-Basket.cpp b/Problems/15-Maximum-Tastiness-of-Candy-Basket/Maximum-Tastiness-of-Candy-Basket.cpp new file mode 100644 index 0000000..80024b7 --- /dev/null +++ b/Problems/15-Maximum-Tastiness-of-Candy-Basket/Maximum-Tastiness-of-Candy-Basket.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + bool check(int x, vector& price, int k) + { + int n = price.size(); + int last = 0; + int idx = 1; + for (int i = 1; i < k; i++) + { + while (idx < n && price[idx] - price[last] < x) idx++; + if (idx == n) return false; + last = idx; + idx++; + } + return true; + } + int maximumTastiness(vector& price, int k) { + sort(price.begin(), price.end()); + int left = 0, right = price[price.size()-1] - price[0]; + int ans = 0; + while (left <= right) + { + int mid = (right-left)/2+left; + if (check(mid, price, k)) + { + ans = mid; + left = mid+1; + } + else right = mid-1; + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/2160.ts b/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/2160.ts new file mode 100644 index 0000000..36cdba1 --- /dev/null +++ b/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/2160.ts @@ -0,0 +1,38 @@ + + +// minimum sum of any length of number. +function minimumSum(num: number): number { + const str = num.toString().split(''); + let digits = str.map(Number); + digits.sort((a,b)=>a-b); + + for(let i = 0; i< digits.length; i++) { + if(digits[i] !== 0) { + digits = digits.slice(i) + break; + } + } + let p1 = 0,p2 = 1; + let num1: number[] = []; + let num2: number[] = []; + while(digits[p1]) { + num1.push(digits[p1]); + if(p2 < digits.length){ + num2.push(digits[p2]) + } + p1 += 2; + p2 += 2; + } + return Num(num1) + Num(num2); + + function Num(digits: number[]): number { + let res : number = 0; + let len = digits.length-1; + for(let i = 0; i < digits.length; i++) { + res += Math.pow(10,len)* digits[i]; + len --; + } + return res; + } + +}; \ No newline at end of file diff --git a/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits.cpp b/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits.cpp new file mode 100644 index 0000000..a4e53f8 --- /dev/null +++ b/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int minimumSum(int num) { + vector v {}; + while(num){ + v.push_back(num % 10); + num /= 10; + } + + sort(v.begin(), v.end()); + + vector a(2, 0); + for (int i = 0; i < v.size(); i++) + { + a[i % 2] = a[i % 2] * 10 + v[i]; + } + return a[0] + a[1]; + } +}; \ No newline at end of file diff --git a/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimun_Sum_of_Four_Digit_Number.py b/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimun_Sum_of_Four_Digit_Number.py new file mode 100644 index 0000000..4b54e9b --- /dev/null +++ b/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits/Minimun_Sum_of_Four_Digit_Number.py @@ -0,0 +1,12 @@ +class Solution(object): + def minimumSum(self, num): + """ + :type num: int + :rtype: int + """ + res = [] + while num: + res.append(num%10) + num/=10 + res.sort() + return res[0]*10+res[2]+ res[1]*10+res[3] \ No newline at end of file diff --git a/Problems/17-Split-a-String-in-Balanced-Strings/1221.ts b/Problems/17-Split-a-String-in-Balanced-Strings/1221.ts new file mode 100644 index 0000000..8c2765c --- /dev/null +++ b/Problems/17-Split-a-String-in-Balanced-Strings/1221.ts @@ -0,0 +1,14 @@ +function balancedStringSplit(s: string): number { + let res: number = 0; + let x:number = 0; + + for(let i of s) { + if( i === 'R') x++; + else x--; + + if(x === 0) { + res ++; + } + } + return res; +}; \ No newline at end of file diff --git a/Problems/17-Split-a-String-in-Balanced-Strings/Split-a-String-in-Balanced-Strings.cpp b/Problems/17-Split-a-String-in-Balanced-Strings/Split-a-String-in-Balanced-Strings.cpp new file mode 100644 index 0000000..fa8d0b4 --- /dev/null +++ b/Problems/17-Split-a-String-in-Balanced-Strings/Split-a-String-in-Balanced-Strings.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int balancedStringSplit(string s) { + int ans = 0; + int cpt = 0; + for (auto& c: s) + { + if (c == 'R') cpt ++; + else cpt --; + + if (cpt == 0) ans ++; + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/17-Split-a-String-in-Balanced-Strings/Split_a_String_in_Balanced_Strings.py b/Problems/17-Split-a-String-in-Balanced-Strings/Split_a_String_in_Balanced_Strings.py new file mode 100644 index 0000000..0632fb6 --- /dev/null +++ b/Problems/17-Split-a-String-in-Balanced-Strings/Split_a_String_in_Balanced_Strings.py @@ -0,0 +1,15 @@ +class Solution(object): + def balancedStringSplit(self, s): + """ + :type s: str + :rtype: int + """ + res, tmp = 0,0 + for char in s: + if char == 'R': + tmp += 1 + else: + tmp -= 1 + if tmp == 0: + res += 1 + return res \ No newline at end of file diff --git a/Problems/18-Can-Place-Flowers/605.ts b/Problems/18-Can-Place-Flowers/605.ts new file mode 100644 index 0000000..d07fca6 --- /dev/null +++ b/Problems/18-Can-Place-Flowers/605.ts @@ -0,0 +1,12 @@ +function canPlaceFlowers(flowerbed: number[], n: number): boolean { + let num: number = 0; + let flag: boolean = false; + for (let i = 0; i < flowerbed.length; i++) { + if (flag === true) i++; + if ((flowerbed[i - 1] === 0 || flowerbed[i - 1] === undefined) && flowerbed[i] === 0 && (flowerbed[i + 1] === 0 || flowerbed[i + 1] === undefined)) { + num++; + flag = true; + } else flag = false; + } + return num >= n; +}; \ No newline at end of file diff --git a/Problems/18-Can-Place-Flowers/Can-Place-Flowers.cpp b/Problems/18-Can-Place-Flowers/Can-Place-Flowers.cpp new file mode 100644 index 0000000..74ef164 --- /dev/null +++ b/Problems/18-Can-Place-Flowers/Can-Place-Flowers.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool canPlaceFlowers(vector& flowerbed, int n) { + + int m = flowerbed.size(); + if (n == 0) return true; + int sum = 0; + for (int j = 0; j < m; j++) + { + if ((j==0 or flowerbed[j-1] == 0) and (j == m-1 or flowerbed[j+1] == 0) and flowerbed[j] == 0) + { + flowerbed[j] = 1; + sum++; + } + } + + return sum >= n; + } +}; \ No newline at end of file diff --git a/Problems/18-Can-Place-Flowers/Can-Place-Flowers.py b/Problems/18-Can-Place-Flowers/Can-Place-Flowers.py new file mode 100644 index 0000000..b4b3da5 --- /dev/null +++ b/Problems/18-Can-Place-Flowers/Can-Place-Flowers.py @@ -0,0 +1,13 @@ +class Solution(object): + def canPlaceFlowers(self, flowerbed, n): + """ + :type flowerbed: List[int] + :type n: int + :rtype: bool + """ + tmp = [0]+flowerbed+[0] + for i in range(1,len(tmp)-1): + if tmp[i-1] == 0 and tmp[i] == 0 and tmp[i+1] == 0: + tmp[i] = 1 + n -= 1 + return n <= 0 diff --git a/Problems/19-Partition-Labels/763.ts b/Problems/19-Partition-Labels/763.ts new file mode 100644 index 0000000..7011261 --- /dev/null +++ b/Problems/19-Partition-Labels/763.ts @@ -0,0 +1,21 @@ +function partitionLabels(s: string): number[] { + + let map: Map = new Map(); + let res: number[] = []; + + for(let i = 0; i < s.length; i++) { + map.set(s[i],i); + } + + let start = 0, end = 0; + for(let i = 0; i < s.length; i++) { + end = Math.max(map.get(s[i])!, end); + if(i === end){ + end = i; + res.push(end - start + 1); + start = end+1; + } + } + return res; + +}; \ No newline at end of file diff --git a/Problems/19-Partition-Labels/Partition-Labels.cpp b/Problems/19-Partition-Labels/Partition-Labels.cpp new file mode 100644 index 0000000..8dc35c0 --- /dev/null +++ b/Problems/19-Partition-Labels/Partition-Labels.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector partitionLabels(string s) { + int n = s.length(); + vector lastPos(26, 0); + for (int i = 0; i < n; i++) + { + lastPos[s[i] - 'a'] = i; + } + + vector ans; + int startIndex = 0; + while (startIndex < n) + { + int j = startIndex; + int endIndex = lastPos[s[startIndex] - 'a']; + while (j < endIndex) + { + if (lastPos[s[j] - 'a'] > endIndex) endIndex = lastPos[s[j] - 'a']; + j++; + } + ans.push_back(endIndex - startIndex + 1); + startIndex = endIndex + 1; + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/19-Partition-Labels/Partition_Labels.py b/Problems/19-Partition-Labels/Partition_Labels.py new file mode 100644 index 0000000..19c5f42 --- /dev/null +++ b/Problems/19-Partition-Labels/Partition_Labels.py @@ -0,0 +1,17 @@ +class Solution(object): + def partitionLabels(self, s): + """ + :type s: str + :rtype: List[int] + """ + last = [0] * 26 + for i in range(len(s)): + last[ord(s[i]) - ord('a')] = i + res = [] + left,right = 0,0 + for i in range(len(s)): + right = max(right, last[ord(s[i]) - ord('a')]) + if i == right: + res.append(right - left + 1) + left = i + 1 + return res \ No newline at end of file diff --git a/Problems/20-Optimal-Partition-of-String/2405.ts b/Problems/20-Optimal-Partition-of-String/2405.ts new file mode 100644 index 0000000..b963f9f --- /dev/null +++ b/Problems/20-Optimal-Partition-of-String/2405.ts @@ -0,0 +1,13 @@ +function partitionString(s: string): number { + let arr: string[] = []; + let count = 0; + for(let i = 0; i < s.length; i++) { + if(arr.indexOf(s[i])>= 0) { + count ++; + arr = []; + } + arr.push(s[i]); + } + return count+1; + +}; \ No newline at end of file diff --git a/Problems/20-Optimal-Partition-of-String/Optimal-Partition-of-String.cpp b/Problems/20-Optimal-Partition-of-String/Optimal-Partition-of-String.cpp new file mode 100644 index 0000000..248ba70 --- /dev/null +++ b/Problems/20-Optimal-Partition-of-String/Optimal-Partition-of-String.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int partitionString(string s) { + int ans = 0; + unordered_set st; + for (auto& c: s) + { + if (st.find(c) == st.end()) + { + st.insert(c); + } + else + { + st.clear(); + st.insert(c); + ans++; + } + } + if (!st.empty()) ans++; + return ans; + } +}; \ No newline at end of file diff --git a/Problems/20-Optimal-Partition-of-String/Optimal_Partition_of_String.py b/Problems/20-Optimal-Partition-of-String/Optimal_Partition_of_String.py new file mode 100644 index 0000000..50c258b --- /dev/null +++ b/Problems/20-Optimal-Partition-of-String/Optimal_Partition_of_String.py @@ -0,0 +1,15 @@ +class Solution(object): + def partitionString(self, s): + """ + :type s: str + :rtype: int + """ + res = 1 + tmp = [] + for char in s: + if char in tmp: + tmp = [char] + res +=1 + else: + tmp.append(char) + return res diff --git a/Problems/21-Minimum-Suffix-Flips/1529.ts b/Problems/21-Minimum-Suffix-Flips/1529.ts new file mode 100644 index 0000000..5064095 --- /dev/null +++ b/Problems/21-Minimum-Suffix-Flips/1529.ts @@ -0,0 +1,13 @@ +function minFlips(target: string): number { + let init = 0; + let flips = 0; + + for(let i = 0; i < target.length; i++) { + if(Number(target[i]) !== init){ + init = Number(target[i]); + flips ++; + } + } + return flips + +}; \ No newline at end of file diff --git a/Problems/21-Minimum-Suffix-Flips/Minimum-Suffix-Flips.cpp b/Problems/21-Minimum-Suffix-Flips/Minimum-Suffix-Flips.cpp new file mode 100644 index 0000000..4ee1280 --- /dev/null +++ b/Problems/21-Minimum-Suffix-Flips/Minimum-Suffix-Flips.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int minFlips(string target) { + int n = target.size(); + int ans = 0; + for (int i = 0; i < n; i++) + { + if ((ans % 2 == 0 && target[i] != '0') || (ans % 2 == 1 && target[i] == '0')) ans++; + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/21-Minimum-Suffix-Flips/Minimum_Suffix_Flips.py b/Problems/21-Minimum-Suffix-Flips/Minimum_Suffix_Flips.py new file mode 100644 index 0000000..504e526 --- /dev/null +++ b/Problems/21-Minimum-Suffix-Flips/Minimum_Suffix_Flips.py @@ -0,0 +1,13 @@ +class Solution(object): + def minFlips(self, target): + """ + :type target: str + :rtype: int + """ + res= 0 + s ="0" + for c in target: + if c != s: + res += 1 + s = c + return res \ No newline at end of file diff --git a/Problems/22-Merge-Strings-Alternately/1768.ts b/Problems/22-Merge-Strings-Alternately/1768.ts new file mode 100644 index 0000000..963b551 --- /dev/null +++ b/Problems/22-Merge-Strings-Alternately/1768.ts @@ -0,0 +1,18 @@ +function mergeAlternately(word1: string, word2: string): string { + let ptr1: number = 0; + let ptr2: number = 0; + const len1 = word1.length; + const len2 = word2.length; + let res: string[] = []; + while (ptr1 < len1 || ptr2 < len2) { + if (ptr1 < len1 && ptr2 < len2) { + res.push(word1[ptr1++]); + res.push(word2[ptr2++]); + } else if (ptr1 > len1 || ptr2 < len2) { + res.push(word2[ptr2++]); + } else if (ptr1 < len1 || ptr2 > len2) { + res.push(word1[ptr1++]); + } + } + return res.join(""); +} diff --git a/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.cpp b/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.cpp new file mode 100644 index 0000000..fc9a370 --- /dev/null +++ b/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + string mergeAlternately(string word1, string word2) { + int n = word1.length(); + int m = word2.length(); + string s = ""; + + int i = 0, j = 0; + while (i < n and j < m) + { + s += word1[i++]; + s += word2[j++]; + } + if (i == n) + { + while (j < m) s+= word2[j++]; + } + if (j == m) + { + while (i < n) s+= word1[i++]; + } + return s; + } +}; \ No newline at end of file diff --git a/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.py b/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.py new file mode 100644 index 0000000..4807a90 --- /dev/null +++ b/Problems/22-Merge-Strings-Alternately/Merge-Strings-Alternately.py @@ -0,0 +1,20 @@ +class Solution(object): + def mergeAlternately(self, word1, word2): + """ + :type word1: str + :type word2: str + :rtype: str + """ + l1 = len(word1) + l2 = len(word2) + i,j = 0,0 + res = list() + while i < l1 or j < l2: + if i < l1: + res.append(word1[i]) + i += 1 + if j < l2: + res.append(word2[j]) + j += 1 + + return "".join(res) \ No newline at end of file diff --git a/Problems/23-Partition-Array-for-Maximum-Sum/1043.ts b/Problems/23-Partition-Array-for-Maximum-Sum/1043.ts new file mode 100644 index 0000000..7ad43b2 --- /dev/null +++ b/Problems/23-Partition-Array-for-Maximum-Sum/1043.ts @@ -0,0 +1,13 @@ +function maxSumAfterPartitioning(arr: number[], k: number): number { + let dp: number[] = []; + dp[0] = 0; + dp[1] = arr[0]; + for (let i = 1; i <= arr.length; i++) { + let m = -1; + for (let j = 1; j <= Math.min(i, k); j++) { + m = Math.max(m, arr[i - j]); + dp[i] = dp[i] ? Math.max(dp[i], dp[i - j] + m * j) : dp[i - j] + m * j; + } + } + return dp[arr.length]; +} diff --git a/Problems/23-Partition-Array-for-Maximum-Sum/Partition-Array-for-Maximum-Sum.cpp b/Problems/23-Partition-Array-for-Maximum-Sum/Partition-Array-for-Maximum-Sum.cpp new file mode 100644 index 0000000..8991569 --- /dev/null +++ b/Problems/23-Partition-Array-for-Maximum-Sum/Partition-Array-for-Maximum-Sum.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + int maxSumAfterPartitioning(vector& arr, int k) { + int n = arr.size(); + vector dp(n+1, 0); + dp[1] = arr[0]; + for (int i = 2; i <= n; i++) + { + long long maxValue = -1; + for (int j = i-1; j >= max(0, i-k); j--) + { + if (arr[j] > maxValue) maxValue = arr[j]; + long long cur = maxValue * (i - j) + dp[j]; + if ( cur > dp[i]) + { + dp[i] = cur; + } + } + } + return dp[n]; + } +}; \ No newline at end of file diff --git a/Problems/23-Partition-Array-for-Maximum-Sum/Partition_Array_for_Max_Sum.py b/Problems/23-Partition-Array-for-Maximum-Sum/Partition_Array_for_Max_Sum.py new file mode 100644 index 0000000..31cc9bd --- /dev/null +++ b/Problems/23-Partition-Array-for-Maximum-Sum/Partition_Array_for_Max_Sum.py @@ -0,0 +1,21 @@ +class Solution(object): + def maxSumAfterPartitioning(self, arr, k): + """ + :type arr: List[int] + :type k: int + :rtype: int + """ + n = len(arr) + res = [0] * (n+1) + + for i in range(1, n+1): + max_val = 0 + for j in range(1, k+1): + pos = i - j + if pos < 0: + break + if arr[pos] > max_val: + max_val = arr[pos] + res[i] = max(res[i], max_val * j + res[pos]) + return res[-1] + \ No newline at end of file diff --git a/Problems/24-Where-Will-the-Ball-Fall/1706.ts b/Problems/24-Where-Will-the-Ball-Fall/1706.ts new file mode 100644 index 0000000..a1c313c --- /dev/null +++ b/Problems/24-Where-Will-the-Ball-Fall/1706.ts @@ -0,0 +1,33 @@ +function findBall(grid: number[][]): number[] { + let m = grid.length; + let n = grid[0].length; + let res: number[] = []; + + for (let i = 0; i < n; i++) { + let x = 0, + y = i; + while (x < m) { + if (grid[x][y] === 1) { + if (y === n - 1) { + break; + } else if (grid[x][y + 1] === -1) { + break; + } + x++; + y++; + } else { + if (y === 0) { + break; + } else if (grid[x][y - 1] === 1) { + break; + } + x++; + y--; + } + } + if (x === m) { + res.push(y); + } else res.push(-1); + } + return res; +} diff --git a/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.cpp b/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.cpp new file mode 100644 index 0000000..03f10ee --- /dev/null +++ b/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + vector findBall(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + + vector> dp(m+1, vector(n, -1)); + for (int j = 0; j < n; j++) dp[m][j] = j; + + for (int i = m-1; i >= 0; i--) + { + for (int j = n-1; j >= 0; j--) + { + if (j != n-1 and grid[i][j+1] == -1 and grid[i][j] == -1) + { + dp[i][j+1] = dp[i+1][j]; + } + else if (j != 0 and grid[i][j-1] == 1 and grid[i][j] == 1) + { + dp[i][j-1] = dp[i+1][j]; + } + } + } + + vector ans(n, 0); + for (int j = 0; j < n; j++) ans[j] = dp[0][j]; + return ans; + } +}; \ No newline at end of file diff --git a/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.py b/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.py new file mode 100644 index 0000000..d3f2587 --- /dev/null +++ b/Problems/24-Where-Will-the-Ball-Fall/Where-Will-the-Ball-Fall.py @@ -0,0 +1,26 @@ +class Solution(object): + def findBall(self, grid): + """ + :type grid: List[List[int]] + :rtype: List[int] + """ + n = len(grid[0]) + ans = [-1] * n + for i in range(n): + col = i + print(col) + for row in grid: + dir = row[col] + col += dir + if col < 0 or col == n or row[col] != dir: + break + else: + ans[i] = col + return ans + + + + + +grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]] +print(Solution().findBall(grid)) \ No newline at end of file diff --git a/Problems/25-Flip-String-to-Monotone-Increasing/926.ts b/Problems/25-Flip-String-to-Monotone-Increasing/926.ts new file mode 100644 index 0000000..a7fe4c3 --- /dev/null +++ b/Problems/25-Flip-String-to-Monotone-Increasing/926.ts @@ -0,0 +1,13 @@ +function minFlipsMonoIncr(s: string): number { + let countOne: number = 0; + let flip: number = 0; + for (let i of s) { + if (i === "1") { + countOne++; + } else { + flip++; + flip = Math.min(countOne, flip); + } + } + return flip; +} diff --git a/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.cpp b/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.cpp new file mode 100644 index 0000000..3e8ebb4 --- /dev/null +++ b/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int minFlipsMonoIncr(string s) { + int n = s.length(); + vector accZero(n+1, 0); + for (int i = n-1; i>= 0; i--) + { + accZero[i] = accZero[i+1]; + if (s[i] == '0') accZero[i]++; + } + + int ans = accZero[0]; + int numOne = 0; + for (int i = 0; i < n ; i++) + { + if (s[i] == '1') numOne++; + ans = min(ans, (numOne + accZero[i+1])); + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.py b/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.py new file mode 100644 index 0000000..10b3ee9 --- /dev/null +++ b/Problems/25-Flip-String-to-Monotone-Increasing/Flip-String-to-Monotone-Increasing.py @@ -0,0 +1,17 @@ +class Solution(object): + def minFlipsMonoIncr(self, s): + """ + :type s: str + :rtype: int + """ + + #使得该分界点之前1的个数和分界点之后0的个数之和最小,把分界点之前的1变成0,之后的0变成1 + m=s.count('0') + res=[m] + for x in s: + if x=='1': + m+=1 + else: + m-=1 + res.append(m) + return min(res) \ No newline at end of file diff --git a/Problems/26-Knight-Dialer/935.ts b/Problems/26-Knight-Dialer/935.ts new file mode 100644 index 0000000..627399b --- /dev/null +++ b/Problems/26-Knight-Dialer/935.ts @@ -0,0 +1,40 @@ +function knightDialer(n: number): number { + let dp: number[][] = new Array(4).fill(new Array(3)); + const M = 1000000007; + dp = [ + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [0, 1, 0], + ]; + + for (let i = 1; i < n; i++) { + let newDp: number[][]; + newDp = [ + [ + (dp[2][1] + dp[1][2]) % M, + (dp[2][0] + dp[2][2]) % M, + (dp[1][0] + dp[2][1]) % M, + ], + [ + (dp[0][2] + dp[2][2] + dp[3][1]) % M, + 0, + (dp[0][0] + dp[2][0] + dp[3][1]) % M, + ], + [ + (dp[0][1] + dp[1][2]) % M, + (dp[0][0] + dp[0][2]) % M, + (dp[1][0] + dp[0][1]) % M, + ], + [0, (dp[1][0] + dp[1][2]) % M, 0], + ]; + dp = newDp; + } + let res = 0; + for (let i = 0; i < 4; i++) { + for (let j = 0; j < 3; j++) { + res += dp[i][j]; + } + } + return res % 1000000007; +} diff --git a/Problems/26-Knight-Dialer/Knight-Dialer.cpp b/Problems/26-Knight-Dialer/Knight-Dialer.cpp new file mode 100644 index 0000000..2a15a34 --- /dev/null +++ b/Problems/26-Knight-Dialer/Knight-Dialer.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int knightDialer(int n) { + const int M = 1000000007; + vector> dp(10, vector(n+1, 0)); + for (int i = 0; i < 10; i++) dp[i][0] = 1; + + for (int j = 1; j < n; j++) + { + dp[1][j] = (dp[6][j-1] + dp[8][j-1]) % M; + dp[2][j] = (dp[7][j-1] + dp[9][j-1]) % M; + dp[3][j] = (dp[4][j-1] + dp[8][j-1]) % M; + dp[4][j] = ((dp[3][j-1] + dp[9][j-1]) % M + dp[0][j-1]) % M; + dp[5][j] = 0; + dp[6][j] = ((dp[1][j-1] + dp[7][j-1]) % M + dp[0][j-1]) % M; + dp[7][j] = (dp[2][j-1] + dp[6][j-1]) % M; + dp[8][j] = (dp[1][j-1] + dp[3][j-1]) % M; + dp[9][j] = (dp[2][j-1] + dp[4][j-1]) % M; + dp[0][j] = (dp[4][j-1] + dp[6][j-1]) % M; + } + int ans = 0; + for (int i = 0; i < 10; i++) ans = (ans + dp[i][n-1]) % M; + return ans; + } +}; \ No newline at end of file diff --git a/Problems/26-Knight-Dialer/Knight-Dialer.py b/Problems/26-Knight-Dialer/Knight-Dialer.py new file mode 100644 index 0000000..2fdb273 --- /dev/null +++ b/Problems/26-Knight-Dialer/Knight-Dialer.py @@ -0,0 +1,18 @@ +class Solution(object): + def knightDialer(self, n): + """ + :type n: int + :rtype: int + """ + if n==1: + return 10 + #A:{1,3,7,9}, B:{2,8}, C:{4,6}, D:{0} + # 处于状态A中的数字(1,3,7,9)通过一次跳跃要么变成状态B(2,8),要么变成状态C(4,6) + # 处于状态B中的数字(2,8)通过一次跳跃有两种方式变成状态A(1,3,7,9) + # 处于状态C中的数字(4,6)通过一次跳跃有两种方式变成状态A(1,3,7,9),还有一种方式变成状态D(0) + # 处于状态D中的数字(0)通过一次跳跃有两种方式变成状态C(4,6) + + nums=[1,1,1,1] + for _ in range(n-1): + nums=[nums[1]+nums[2], 2*nums[0], 2*nums[0]+nums[3], 2*nums[2]] + return (4*nums[0]+2*nums[1]+2*nums[2]+nums[3])%1000000007 diff --git a/Problems/27-Ways-to-Make-a-Fair-Array/1664.ts b/Problems/27-Ways-to-Make-a-Fair-Array/1664.ts new file mode 100644 index 0000000..238d6f4 --- /dev/null +++ b/Problems/27-Ways-to-Make-a-Fair-Array/1664.ts @@ -0,0 +1,25 @@ +function waysToMakeFair(nums: number[]): number { + const n: number = nums.length; + nums.unshift(0); + let leftEven: number[] = new Array(n + 1).fill(0); + let leftOdd: number[] = new Array(n + 1).fill(0); + let leftEvenSum = 0, + leftOddSum = 0; + for (let i = 1; i <= n; i++) { + if (i % 2 === 0) leftEvenSum += nums[i]; + else leftOddSum += nums[i]; + leftEven[i] = leftEvenSum; + leftOdd[i] = leftOddSum; + } + let rightEvenSum = 0, + rightOddSum = 0; + let res = 0; + for (let i = n; i >= 1; i--) { + if (leftEven[i - 1] + rightOddSum === leftOdd[i - 1] + rightEvenSum) { + res++; + } + if (i % 2 === 0) rightEvenSum += nums[i]; + else rightOddSum += nums[i]; + } + return res; +} diff --git a/Problems/27-Ways-to-Make-a-Fair-Array/Ways-to-Make-a-Fair-Array.cpp b/Problems/27-Ways-to-Make-a-Fair-Array/Ways-to-Make-a-Fair-Array.cpp new file mode 100644 index 0000000..11e08fa --- /dev/null +++ b/Problems/27-Ways-to-Make-a-Fair-Array/Ways-to-Make-a-Fair-Array.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + int waysToMakeFair(vector& nums) { + int n = nums.size(); + if (n == 1) return 1; + + vector v(n, 0); + v[0] = nums[0]; + v[1] = nums[1]; + + for (int i = 2; i < n; i++) + { + v[i] = v[i-2] + nums[i]; + } + + int lastEven = (n % 2 == 0)?(n-2):(n-1); + int lastOdd = (n % 2 == 1)?(n-2):(n-1); + + int ans = 0; + for (int i = 0; i < n; i++) + { + if (i == 0) + { + if (v[lastEven] - v[0] == v[lastOdd]) ans++; + } + else if (i == 1) + { + if (v[0] + v[lastOdd] - v[1] == v[lastEven] - v[0]) ans++; + } + else + if (i % 2 == 0) + { + auto sumEven = v[i-2] + v[lastOdd] - v[i-1]; + auto sumOdd = v[i-1] + v[lastEven] - v[i]; + if (sumEven == sumOdd) ans++; + } + else + { + auto sumEven = v[i-1] + v[lastOdd] - v[i]; + auto sumOdd = v[i-2] + v[lastEven] - v[i-1]; + if (sumEven == sumOdd) ans++; + + } + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/1884.ts b/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/1884.ts new file mode 100644 index 0000000..c432a4f --- /dev/null +++ b/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/1884.ts @@ -0,0 +1,21 @@ +function twoEggDrop(n: number): number { + + let dp : number[][] = Array.from(Array(3), () => new Array(n+1)) + + dp[1][0] = 0; + dp[2][0] = 0; + + for(let i = 1; i <= n; i++) { + dp[1][i] = i; + } + + for(let i = 1; i <= n; i++) { + for(let j = 1; j <= i; j++) { + dp[2][i] = dp[2][i]!==undefined? Math.min(dp[2][i], 1+Math.max(dp[1][j-1],dp[2][i-j])) : 1+Math.max(dp[1][j-1],dp[2][i-j]) + } + } + + return dp[2][n]; + + +}; \ No newline at end of file diff --git a/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/Egg-Drop-With-2-Eggs-and-N-Floors.cpp b/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/Egg-Drop-With-2-Eggs-and-N-Floors.cpp new file mode 100644 index 0000000..4319af8 --- /dev/null +++ b/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors/Egg-Drop-With-2-Eggs-and-N-Floors.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int solve(int k, int n, vector& dp) + { + if (k == 1) return n; + if (dp[n] != 0) return dp[n]; + for (int i = 1; i <= n; i++) + { + int tmp = 1 + max(solve(k-1, i-1, dp), solve(k, n-i, dp)); + if (dp[n] == 0) dp[n] = tmp; + else dp[n] = min(dp[n], tmp); + } + return dp[n]; + } + + int twoEggDrop(int n) { + vector dp(n+1, 0); + return solve(2, n, dp); + } +}; \ No newline at end of file diff --git a/Problems/29-Number-of-Good-Ways-to-Split-a-String/1525.ts b/Problems/29-Number-of-Good-Ways-to-Split-a-String/1525.ts new file mode 100644 index 0000000..5b03cfc --- /dev/null +++ b/Problems/29-Number-of-Good-Ways-to-Split-a-String/1525.ts @@ -0,0 +1,19 @@ +function numSplits(s: string): number { + const left_set = new Set(); + const right_set = new Set(); + let arr = []; + let res = 0; + + for(let i=0; i=0; i--) { + right_set.add(s[i]); + if(right_set.size === arr[i-1]){ + res++ + } + } + return res; + +}; \ No newline at end of file diff --git a/Problems/29-Number-of-Good-Ways-to-Split-a-String/Number-of-Good-Ways-to-Split-a-String.cpp b/Problems/29-Number-of-Good-Ways-to-Split-a-String/Number-of-Good-Ways-to-Split-a-String.cpp new file mode 100644 index 0000000..c644d64 --- /dev/null +++ b/Problems/29-Number-of-Good-Ways-to-Split-a-String/Number-of-Good-Ways-to-Split-a-String.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int numSplits(string s) { + int n = s.length(); + vector right(n+1, 0); + + unordered_set ss; + for (int i = n-1; i >= 0; i--) + { + ss.insert(s[i]); + right[i] = ss.size(); + } + + ss.clear(); + int ans = 0; + for (int i = 0; i < n; i++) + { + ss.insert(s[i]); + if (ss.size() == right[i+1]) ans++; + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/30-Minimum-Sideway-Jumps/Minimum-Sideway-Jumps.cpp b/Problems/30-Minimum-Sideway-Jumps/Minimum-Sideway-Jumps.cpp new file mode 100644 index 0000000..8788a8c --- /dev/null +++ b/Problems/30-Minimum-Sideway-Jumps/Minimum-Sideway-Jumps.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int minSideJumps(vector& obstacles) { + int n = obstacles.size(); + vector> dp(n, vector(3,0)); + dp[0][0] = dp[0][2] = 1; + + for (int i = 1; i < n; i++) + { + for (int j = 0; j < 3; j++) + { + dp[i][j] = INT_MAX-1; + if (obstacles[i] - 1 == j) continue; + + if (obstacles[i-1] -1 != j) dp[i][j] = min(dp[i][j], dp[i-1][j]); + + int lane = (j+1) % 3; + if (obstacles[i-1] -1 != lane && obstacles[i] -1 != lane) dp[i][j] = min(dp[i][j], dp[i-1][lane]+1); + + lane = (j+2) % 3; + if (obstacles[i-1] -1 != lane && obstacles[i] -1 != lane) dp[i][j] = min(dp[i][j], dp[i-1][lane]+1); + } + } + + int ans = INT_MAX; + for (int j = 0; j < 3; j++) ans = min(ans, dp[n-1][j]); + return ans; + } +}; \ No newline at end of file diff --git a/Problems/31-Delete-and-Earn/Delete-and-Earn.cpp b/Problems/31-Delete-and-Earn/Delete-and-Earn.cpp new file mode 100644 index 0000000..857a784 --- /dev/null +++ b/Problems/31-Delete-and-Earn/Delete-and-Earn.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int deleteAndEarn(vector& nums) { + unordered_map m; + for (auto x: nums) m[x]++; + + vector dp(10001, 0); + dp[1] = m[1]; + for (int i = 2; i <= 10000; i++) + { + dp[i] = max(dp[i-2] + i * m[i], dp[i-1]); + } + return dp[10000]; + } +}; \ No newline at end of file diff --git a/Problems/32-Minimum-Total-Importance-of-Roads/Minimum-Total-Importance-of-Roads.cpp b/Problems/32-Minimum-Total-Importance-of-Roads/Minimum-Total-Importance-of-Roads.cpp new file mode 100644 index 0000000..7ad49c5 --- /dev/null +++ b/Problems/32-Minimum-Total-Importance-of-Roads/Minimum-Total-Importance-of-Roads.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + long long maximumImportance(int n, vector>& roads) { + vector a(50000, 0); + for (auto& e: roads) + { + a[e[0]]++; + a[e[1]]++; + } + + sort(a.begin(), a.end()); + long long ans = 0; + long long j = n; + for (int i = 50000-1; i >=0; i--) + { + if (a[i]) + { + ans += a[i] * j; + j--; + } + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/33-Maximum-Star-Sum-of-Graph/Maximum-Star-Sum-of-Graph.cpp b/Problems/33-Maximum-Star-Sum-of-Graph/Maximum-Star-Sum-of-Graph.cpp new file mode 100644 index 0000000..a67f26b --- /dev/null +++ b/Problems/33-Maximum-Star-Sum-of-Graph/Maximum-Star-Sum-of-Graph.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + int maxStarSum(vector& vals, vector>& edges, int k) { + int n = vals.size(); + vector> a(n, vector()); + + for (auto& e: edges) + { + a[e[0]].push_back(vals[e[1]]); + a[e[1]].push_back(vals[e[0]]); + } + + for (int i = 0; i < n; i++) + { + sort(a[i].begin(), a[i].end(), greater()); + } + + int ans = INT_MIN; + for (int i = 0; i < n; i++) + { + int sum = vals[i]; + int m = (k < a[i].size())?k:a[i].size(); + for (int j = 0; j < m; j++) + { + if (a[i][j] > 0) sum += a[i][j]; + else break; + } + if (sum > ans) ans = sum; + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/34-Course-Schedule-IV/Course-Schedule-IV.cpp b/Problems/34-Course-Schedule-IV/Course-Schedule-IV.cpp new file mode 100644 index 0000000..e525c6d --- /dev/null +++ b/Problems/34-Course-Schedule-IV/Course-Schedule-IV.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector checkIfPrerequisite(int numCourses, vector>& prerequisites, vector>& queries) { + vector> dp(numCourses, vector(numCourses, false)); + for (auto& e: prerequisites) + { + dp[e[0]][e[1]] = true; + } + + for (int k = 0; k < numCourses; k++) + for (int i = 0; i < numCourses; i++) + for (int j = 0; j < numCourses; j++) + { + dp[i][j] = dp[i][j] or (dp[i][k] and dp[k][j]); + } + + vector ans; + for (auto& q: queries) + { + ans.push_back(dp[q[0]][q[1]]); + } + return ans; + } +}; \ No newline at end of file diff --git a/Problems/Weekly-Contest-329/Alternating-Digit-Sum.cpp b/Problems/Weekly-Contest-329/Alternating-Digit-Sum.cpp new file mode 100644 index 0000000..c3791e8 --- /dev/null +++ b/Problems/Weekly-Contest-329/Alternating-Digit-Sum.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; +class Solution { +public: + int alternateDigitSum(int n) { + std::string s = to_string(n); + int sum = 0; + int sign = 1; + for (int i = 0 ; i < s.length(); i++) + { + sum += sign * (s[i] - '0'); + sign *= -1; + } + return sum; + } +}; \ No newline at end of file diff --git a/Problems/Weekly-Contest-329/Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp b/Problems/Weekly-Contest-329/Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp new file mode 100644 index 0000000..9551018 --- /dev/null +++ b/Problems/Weekly-Contest-329/Apply-Bitwise-Operations-to-Make-Strings-Equal.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; + +class Solution { +public: + bool makeStringsEqual(string s, string target) { + bool has1_s = false, has1_target = false; + for (int i = 0; i < s.length(); i++) + { + if (s[i] == '1') has1_s = true; + if (target[i] == '1') has1_target = true; + } + return (s == target or (has1_s and has1_target)); + } +}; + diff --git a/Problems/Weekly-Contest-329/Minimum-Cost-to-Split-an-Array.cpp b/Problems/Weekly-Contest-329/Minimum-Cost-to-Split-an-Array.cpp new file mode 100644 index 0000000..c3ce591 --- /dev/null +++ b/Problems/Weekly-Contest-329/Minimum-Cost-to-Split-an-Array.cpp @@ -0,0 +1,36 @@ +#include +uisng namespace std; + +class Solution { +public: + int minCost(vector& nums, int k) { + int n = nums.size(); + + vector dp(n+1, 0); + dp[0] = k; + for (int i = 1; i < n; i++) + { + unordered_map counter; + int numberOfUniqueElement = 0; + long long minCost = -1; + for (int j = i; j >= 0; j--) + { + counter[nums[j]]++; + if (counter[nums[j]] == 1) numberOfUniqueElement++; + if (counter[nums[j]] == 2) numberOfUniqueElement--; + long long importance = k + (i - j + 1 - numberOfUniqueElement); + + long long cost = (j == 0)?importance:importance + dp[j-1]; + + if (minCost == -1) minCost = cost; + else if (minCost > cost) + { + minCost = cost; + } + dp[i] = minCost; + } + } + + return dp[n-1]; + } +}; diff --git a/Problems/Weekly-Contest-329/Sort-the-Students-by-Their-Kth-Score.cpp b/Problems/Weekly-Contest-329/Sort-the-Students-by-Their-Kth-Score.cpp new file mode 100644 index 0000000..0ad84f2 --- /dev/null +++ b/Problems/Weekly-Contest-329/Sort-the-Students-by-Their-Kth-Score.cpp @@ -0,0 +1,9 @@ +#include +using namespace std; +class Solution { +public: + vector> sortTheStudents(vector>& score, int k) { + sort(score.begin(), score.end(), [k](const vector& a, const vector& b){ return a[k] > b[k]; }); + return score; + } +}; \ No newline at end of file diff --git a/README.md b/README.md index c951557..60e20a8 100644 --- a/README.md +++ b/README.md @@ -9,4 +9,42 @@ Solutions in various programming languages are provided. Enjoy it. 1. 2023/01/23 [#100 Same Tree ](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/01-Same-Tree): Tree, Recursive 2. 2023/01/24 [#101 Symmetric Tree ](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/02-Symmetric-Tree): Tree, Recursive 3. 2023/01/25 [#110 Balanced Binary Tree](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/03-Balanced-Binary-Tree): Tree, Recursive +4. 2023/01/26 [#112 Path Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/04-Path-Sum): Tree, Recursive +5. 2023/01/27 [#530 Minimum Absolute Difference in BST](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/05-Minimum-Absolute-Difference-in-BST): BST, Tree Traversal +6. 2023/01/28 [#235 Lowest Common Ancestor of a Binary Search Tree](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/06-Lowest-Common-Ancestor-of-a-Binary-Search-Tree): Tree, LCA +7. 2023/01/29 [#1305 All Elements in Two Binary Search Trees](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/07-All-Elements-in-Two-Binary-Search-Trees): Tree Traversal +8. 2023/01/30 [#35 Search Insert Position](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/08-Search-Insert-Position): Binary Search +9. 2023/01/31 [#2389 Longest Subsequence With Limited Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/09-Longest-Subsequence-With-Limited-Sum): Binary Search +10. 2023/02/01 [#1385 Find the Distance Value Between Two Arrays](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/10-Find-the-Distance-Value-Between-Two-Arrays): Binary Search +11. 2023/02/02 [#374 Guess Number Higher or Lower](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/11-Guess-Number-Higher-or-Lower): Binary Search +12. 2023/02/03 [#34 Find First and Last Position of Element in Sorted Array](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/12-Find-First-and-Last-Position-of-Element-in-Sorted-Array): Binary Search +13. 2023/02/04 [#1004. Max Consecutive Ones III](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/13-Max-Consecutive-Ones-III): Binary Search +14. 2023/02/05 [#74. Search a 2D Matrix](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/14-Search-a-2D-Matrix): Binary Search +15. 2023/02/06 [#2517. Maximum Tastiness of Candy Basket](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/15-Maximum-Tastiness-of-Candy-Basket): Binary Search +16. 2023/02/07 [#2160 Minimum Sum of Four Digit Number After Splitting Digits](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/16-Minimum-Sum-of-Four-Digit-Number-After-Splitting-Digits): Greedy +17. 2023/02/08 [#1221 Split a String in Balanced Strings](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/17-Split-a-String-in-Balanced-Strings): Greedy +18. 2023/02/09 [#605 Can Place Flowers](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/18-Can-Place-Flowers): Greedy +19. 2023/02/10 [#763 Partition Labels](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/19-Partition-Labels): Greedy +20. 2023/02/11 [#2405 Optimal Partition of String](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/20-Optimal-Partition-of-String): Greedy +21. 2023/02/12 [#1529 Minimum Suffix Flips](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/21-Minimum-Suffix-Flips): Greedy +22. 2023/02/13 [#1768 Merge Strings Alternately](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/22-Merge-Strings-Alternately): String +23. 2023/02/14 [#1043 Partition Array for Maximum Sum](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/23-Partition-Array-for-Maximum-Sum): DP +24. 2023/02/15 [#1706 Where Will the Ball Fall](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/24-Where-Will-the-Ball-Fall): DP +25. 2023/02/16 [#926 Flip String to Monotone Increasing](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/25-Flip-String-to-Monotone-Increasing): DP +26. 2023/02/17 [#935 Knight Dialer](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/26-Knight-Dialer): DP +27. 2023/02/18 [#1664 Ways to Make a Fair Array](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/27-Ways-to-Make-a-Fair-Array): DP +28. 2023/02/19 [#1884 Egg Drop With 2 Eggs and N Floors](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/28-Egg-Drop-With-2-Eggs-and-N-Floors): DP +29. 2023/02/20 [#1525 Number of Good Ways to Split a String](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/29-Number-of-Good-Ways-to-Split-a-String): DP +30. 2023/02/21 [#1824 Minimum Sideway Jumps](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/30-Minimum-Sideway-Jumps): DP +31. 2023/02/22 [#740 Delete and Earn](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/31-Delete-and-Earn): DP +32. 2023/02/23 [#2285 Maximum Total Importance of Roads](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/32-Minimum-Total-Importance-of-Roads): Star Graph +33. 2023/02/24 [#2497 Maximum Star Sum of a Graph](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/33-Maximum-Star-Sum-of-Graph): Star Graph +34. 2023/02/25 [#1462 Course Schedule IV](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/34-Course-Schedule-IV): Graph, Floyd +## Weekly Contest + +### [Weekly Contest 329](https://github.com/LeetcodeRush/Leetcode/tree/main/Problems/Weekly-Contest-329) +* #2544 Alternating Digit Sum: Maths +* #2545 Sort the Students by Their Kth Score: Customized Sort +* #2546 Apply Bitwise Operations to Make Strings Equal: Maths +* #2547 Minimum Cost to Split an Array: DP